Part Number Hot Search : 
SDM10K45 A7303 KSH122I THN5601B 74HC4050 TLE4263 NNCD24DA BG103
Product Description
Full Text Search
 

To Download ATTINY2313V-10SI Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
  2543f?avr?08/04 features  utilizes the avr ? risc architecture  avr ? high-performance and low-power risc architecture ? 120 powerful instructions ? most single clock cycle execution ? 32 x 8 general purpose working registers ? fully static operation ? up to 20 mips throughput at 20 mhz  data and non-volatile pr ogram and data memories ? 2k bytes of in-system self programmable flash endurance 10,000 write/erase cycles ? 128 bytes in-system programmable eeprom endurance: 100,000 write/erase cycles ? 128 bytes internal sram ? programming lock for flash pr ogram and eeprom data security  peripheral features ? one 8-bit timer/counter with se parate prescaler and compare mode ? one 16-bit timer/counter with separate prescaler, compare and capture modes ? four pwm channels ? on-chip analog comparator ? programmable watchdog timer with on-chip oscillator ? usi ? universal serial interface ? full duplex usart  special microcontroller features ? debugwire on-chip debugging ? in-system programmable via spi port ? external and internal interrupt sources ? low-power idle, power-down, and standby modes ? enhanced power-on reset circuit ? programmable brown-out detection circuit ? internal calibrated oscillator  i/o and packages ? 18 programmable i/o lines ? 20-pin pdip, 20-pin soic, and 32-pin mlf  operating voltages ? 1.8 - 5.5v (attiny2313v) ? 2.7 - 5.5v (attiny2313)  speed grades ? attiny2313v: 0 - 4 mhz @ 1.8 - 5.5v, 0 - 10 mhz @ 2.7 - 5.5v ? attiny2313: 0 - 10 mhz @ 2.7 - 5.5v, 0 - 20 mhz @ 4.5 - 5.5v  typical power consumption ? active mode 1 mhz, 1.8v: 230 a 32 khz, 1.8v: 20 a (including oscillator) ? power-down mode < 0.1 a at 1.8v 8-bit microcontroller with 2k bytes in-system programmable flash attiny2313/v preliminary rev. 2543f?avr?08/04
2 attiny2313/v 2543f?avr?08/04 pin configurations figure 1. pinout attiny2313 overview the attiny2313 is a low-power cmos 8-bit microcontroller based on the avr enhanced risc architecture. by executing powe rful instructions in a single clock cycle, the attiny2313 achieves throughputs approaching 1 mips per mhz allowing the system designer to optimize power consum ption versus processing speed. (reset/dw)pa2 (rxd)pd0 (txd)pd1 (xtal2)pa1 (xtal1)pa0 (ckout/xck/int0)pd2 (int1)pd3 (t0)pd4 (oc0b/t1)pd5 gnd 20 19 18 17 16 15 14 13 12 11 1 2 3 4 5 6 7 8 9 10 vcc pb7(ucsk/sck/pcint7) pb6(miso/do/pcint6) pb5(mosi/di/sda/pcint5) pb4(oc1b/pcint4) pb3(oc1a/pcint3) pb2(oc0a/pcint2) pb1(ain1/pcint1) pb0(ain0/pcint0) pd6(icp) pdip/soic
3 attiny2313/v 2543f?avr?08/04 block diagram figure 2. block diagram program counter program flash instruction register gnd vcc instruction decoder control lines stack pointer sram general purpose register alu status register programming logic spi 8-bit data bus xtal1 xtal2 reset internal oscillator oscillator watchdog timer timing and control mcu control register mcu status register timer/ counters interrupt unit eeprom usi usart analog comparator data register portb data dir. reg. portb data register porta data dir. reg. porta portb drivers pb0 - pb7 porta drivers pa0 - pa2 data register portd data dir. reg. portd portd drivers pd0 - pd6 on-chip debugger internal calibrated oscillator
4 attiny2313/v 2543f?avr?08/04 the avr core combines a rich instruction se t with 32 general purpose working registers. all the 32 registers are directly connected to the arithmetic logic unit (alu), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. the resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional cisc microcontrollers. the attiny2313 provides the following features: 2k bytes of in-system programmable flash, 128 bytes eepr om, 128 bytes sram, 18 general purpose i/o lines , 32 general purpose working registers, a single-wire interface for on-chip debugging, two flexible timer/counters with compare modes, internal and external interrupts, a serial program- mable usart, universal serial interface with start condition detector, a programmable watchdog timer with internal oscillator, and three software selectable power saving modes. the idle mode stops the cpu while allowing the sram, timer/counters, and interrupt system to continue functioning. the power-down mode saves the register con- tents but freezes the oscillator, disabling al l other chip functions until the next interrupt or hardware reset. in standby mode, the crystal/resonato r oscillator is ru nning while the rest of the device is sleeping. this allows very fast start-up co mbined with low-power consumption. the device is manufactured using atmel?s high density non-volatile memory technology. the on-chip isp flash allows the program memory to be reprogrammed in-system through an spi serial interface, or by a conventional non-volatile memory programmer. by combining an 8-bit risc cpu with in-system self-programmable flash on a mono- lithic chip, the atmel attiny2313 is a powerful microcontroller that provides a highly flexible and cost effective solution to many embedded control applications. the attiny2313 avr is supported with a full suite of program and system development tools including: c compilers, macro assemblers, program debugger/simulators, in-cir- cuit emulators, and evaluation kits.
5 attiny2313/v 2543f?avr?08/04 pin descriptions vcc digital supply voltage. gnd ground. port a (pa2..pa0) port a is a 3-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port a output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port a pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port a pins are tri-stated when a reset condition becomes active, even if the clock is not running. port a also serves the functions of various special features of the attiny2313 as listed on page 52. port b (pb7..pb0) port b is an 8-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port b output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port b pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port b pins are tri-stated when a reset condition becomes active, even if the clock is not running. port b also serves the functions of various special features of the attiny2313 as listed on page 52. port d (pd6..pd0) port d is a 7-bit bi-directional i/o port with internal pull-up resistors (selected for each bit). the port d output buffers have symmetrical drive characteristics with both high sink and source capability. as inputs, port d pi ns that are externally pulled low will source current if the pull-up resistors are activated. the port d pins are tri-stated when a reset condition becomes active, even if the clock is not running. port d also serves the functions of variou s special features of the attiny2313 as listed on page 55. reset reset input. a low level on this pin for longer than the minimu m pulse length will gener- ate a reset, even if the clock is not running. the minimum pulse length is given in table 15 on page 33. shorter pulses are not guaranteed to generate a reset. the reset input is an alternate function for pa2 and dw. xtal1 input to the inverting oscillato r amplifier and input to the in ternal clock operating circuit. xtal1 is an alternate function for pa0. xtal2 output from the inverting os cillator amplifier. xtal2 is an alternate f unction for pa1. about code examples this documentation contains simple code examples that briefly show how to use various parts of the device. these code examples assume that the part specific header file is included before compilation. be aware that not all c compiler vendors include bit defini- tions in the header files and interrupt handling in c is compiler dependent. please confirm with the c compiler documentation for more details. disclaimer typical values contained in this data sheet are based on simulations and characteriza- tion of other avr microcontrollers manufactured on the same process technology. min and max values will be available afte r the device is characterized.
6 attiny2313/v 2543f?avr?08/04 avr cpu core introduction this section discusses the avr core archit ecture in general. the main function of the cpu core is to ensure correct program execution. the cpu must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts. architectural overview figure 3. block diagram of the avr architecture in order to maximize performance and para llelism, the avr uses a harvard architecture ? with separate memories and buses for program and data. instructions in the program memory are executed with a single level pipel ining. while one instruction is being exe- cuted, the next instruction is pre-fetched from the program memory. this concept enables instructions to be executed in every clock cycle. the program memory is in- system reprogrammable flash memory. the fast-access register file contains 32 x 8-bit general purpose working registers with a single clock cycle access time. this allows single-cycle arithmetic logic unit (alu) operation. in a typical alu operation, two operands are output from the register file, flash program memory instruction register instruction decoder program counter control lines 32 x 8 general purpose registrers alu status and control i/o lines eeprom data bus 8-bit data sram direct addressing indirect addressing interrupt unit spi unit watchdog timer analog comparator i/o module 2 i/o module1 i/o module n
7 attiny2313/v 2543f?avr?08/04 the operation is executed, and the result is stored back in the register file ? in one clock cycle. six of the 32 registers can be used as three 16-bit indirect address register pointers for data space addressing ? enabling efficient address calculations. one of the these address pointers can also be used as an addr ess pointer for look up tables in flash pro- gram memory. these added function registers are the 16-bit x-, y-, and z-register, described later in this section. the alu supports arithmetic and logic operations between registers or between a con- stant and a register. single register operations can also be executed in the alu. after an arithmetic operation, the status register is updated to reflect information about the result of the operation. program flow is provided by conditional and unconditional jump and call instructions, able to directly address the whole address s pace. most avr instructions have a single 16-bit word format. every program memory address contains a 16- or 32-bit instruction. during interrupts and subroutine calls, the return address program counter (pc) is stored on the stack. the stack is effectively allocated in the general data sram, and consequently the stack size is only limited by the total sram size and the usage of the sram. all user programs must initialize the sp in the reset routine (before subroutines or interrupts are executed). the stack pointer (sp) is read/write accessible in the i/o space. the data sram can easily be accessed through the five different addressing modes supported in the avr architecture. the memory spaces in the avr architecture are all linear and regular memory maps. a flexible interrupt module has its control registers in the i/o space with an additional global interrupt enable bit in the status register. all interrupts have a separate interrupt vector in the interrupt vector table. the interrupts have priority in accordance with their interrupt vector position. the lower the interrupt vector address, the higher the priority. the i/o memory space contains 64 addresse s for cpu peripheral functions as control registers, and other i/o functions. the i/o memory can be accessed directly, or as the data space locations following those of the register file, 0x20 - 0x5f. alu ? arithmetic logic unit the high-performance avr alu operates in direct connection with all the 32 general purpose working registers. within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. the alu operations are divided into three main categories ? arithmetic, logical, and bit-func- tions. some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format. see the ?instruc- tion set? section for a detailed description. status register the status register contains information about the result of the most recently executed arithmetic instruction. this information can be used for altering program flow in order to perform conditional operations. note that the status register is updated after all alu operations, as specified in the instructio n set reference. this will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. the status register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. this must be handled by software.
8 attiny2313/v 2543f?avr?08/04 the avr status register ? sreg ? is defined as:  bit 7 ? i: global interrupt enable the global interrupt enable bit must be set for the interrupts to be enabled. the individ- ual interrupt enable control is then performed in separate control registers. if the global interrupt enable register is cleared, n one of the interrupts are enabled independent of the individual interrupt enable settings. the i-bit is cleared by hardware after an interrupt has occurred, and is set by the reti instruction to enable subsequent interrupts. the i- bit can also be set and cleared by the application with the sei and cli instructions, as described in the instruction set reference.  bit 6 ? t: bit copy storage the bit copy instructions bld (bit load) and bst (bit store) use the t-bit as source or destination for the operated bit. a bit from a register in the register file can be copied into t by the bst instruction, and a bit in t can be copied into a bit in a register in the register file by the bld instruction.  bit 5 ? h: half carry flag the half carry flag h indicates a half carry in some arithmetic operations. half carry is useful in bcd arithmetic. see the ?instruction set description? for detailed information.  bit 4 ? s: sign bit, s = n v the s-bit is always an exclusive or betwe en the negative flag n and the two?s comple- ment overflow flag v. see the ?instruction set description? for detailed information.  bit 3 ? v: two?s complement overflow flag the two?s complement overflow flag v supports two?s complement arithmetics. see the ?instruction set description? for detailed information.  bit 2 ? n: negative flag the negative flag n indicates a negative result in an arithmetic or logic operation. see the ?instruction set description? for detailed information.  bit 1 ? z: zero flag the zero flag z indicates a zero result in an arithmetic or logic operation. see the ?instruction set description? for detailed information.  bit 0 ? c: carry flag the carry flag c indicates a carry in an arit hmetic or logic operation. see the ?instruc- tion set description? for detailed information. general purpose register file the register file is optimized for the avr enhanced risc instruction set. in order to achieve the required performance and flexib ility, the following inpu t/output schemes are supported by the register file:  one 8-bit output operand and one 8-bit result input  two 8-bit output operands and one 8-bit result input  two 8-bit output operands and one 16-bit result input  one 16-bit output operand and one 16-bit result input figure 4 shows the structure of the 32 general purpose working registers in the cpu. bit 76543210 ithsvnzcsreg read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
9 attiny2313/v 2543f?avr?08/04 figure 4. avr cpu general purpose working registers most of the instructions operating on the register file have direct access to all registers, and most of them are single cycle instructions. as shown in figure 4, each register is also assigned a data memory address, mapping them directly into the first 32 locations of the user data space. although not being phys- ically implemented as sram locations, this memory organization provides great flexibility in access of the registers, as t he x-, y- and z-pointer registers can be set to index any register in the file. the x-register, y-register, and z-register the registers r26..r31 have some added f unctions to their general purpose usage. these registers are 16-bit address pointers for indirect addressing of the data space. the three indirect address registers x, y, and z are defined as described in figure 5. figure 5. the x-, y-, and z-registers in the different addressing modes these addres s registers have functions as fixed dis- placement, automatic increment, and automatic decrement (see the instruction set reference for details). 7 0 addr. r0 0x00 r1 0x01 r2 0x02 ? r13 0x0d general r14 0x0e purpose r15 0x0f working r16 0x10 registers r17 0x11 ? r26 0x1a x-register low byte r27 0x1b x-register high byte r28 0x1c y-register low byte r29 0x1d y-register high byte r30 0x1e z-register low byte r31 0x1f z-register high byte 15 xh xl 0 x-register 707 0 r27 (0x1b) r26 (0x1a) 15 yh yl 0 y-register 707 0 r29 (0x1d) r28 (0x1c) 15 zh zl 0 z-register 70 7 0 r31 (0x1f) r30 (0x1e)
10 attiny2313/v 2543f?avr?08/04 stack pointer the stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. the stack pointer regis- ter always points to the top of the stack. note that the stack is implemented as growing from higher memory locations to lower memory locations. this implies that a stack push command decreases the stack pointer. the stack pointer points to the data sram stack area where the subroutine and inter- rupt stacks are located. this stack space in the data sram must be defined by the program before any subroutine calls are executed or interrupts are enabled. the stack pointer must be set to point above 0x60. the stack pointer is decremented by one when data is pushed onto the stack with the push instruction, and it is decremented by two when the return address is pushed onto the stack with subroutine call or interrupt. the stack pointer is incremented by one when data is popped from the stack with the pop instruction, and it is incremented by two when data is popped from the stack with return from subroutine ret or return from interrupt reti. the avr stack pointer is implemented as two 8-bit registers in the i/o space. the num- ber of bits actually used is implementation dependent. note that the data space in some implementations of the avr architecture is so small that only spl is needed. in this case, the sph register will not be present. instruction execution timing this section describes the general access timing concepts for instruction execution. the avr cpu is driven by the cpu clock clk cpu , directly generated from the selected clock source for the chip. no intern al clock division is used. figure 6 shows the parallel instruction fetches and instruction executions enabled by the harvard architecture and the fast-access register file concept. this is the basic pipelin- ing concept to obtain up to 1 mips per mhz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. figure 6. the parallel instruction fetches and instruction executions figure 7 shows the internal timing concept fo r the register file. in a single clock cycle an alu operation using two register operands is executed, and the result is stored back to the destination register. bit 151413121110 9 8 ????????sph sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 spl 76543210 read/writerrrrrrrr r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 00000000 clk 1st instruction fetch 1st instruction execute 2nd instruction fetch 2nd instruction execute 3rd instruction fetch 3rd instruction execute 4th instruction fetch t1 t2 t3 t4 cpu
11 attiny2313/v 2543f?avr?08/04 figure 7. single cycle alu operation reset and interrupt handling the avr provides several different interrupt sources. these interrupts and the separate reset vector each have a separate program vector in the program memory space. all interrupts are assigned individual enable bits which must be written logic one together with the global interrupt enable bit in the status register in order to enable the interrupt. the lowest addresses in the program memory space are by default defined as the reset and interrupt vectors. the complete list of vectors is shown in ?interrupts? on page 43. the list also determines the priority levels of the different interrupts. the lower the address the higher is the priori ty level. reset has the high est priority, and next is int0 ? the external interrupt request 0. refer to ?interrupts? on page 43 for more information. when an interrupt occurs, the global interrupt enable i-bit is cleared and all interrupts are disabled. the user software can write logic one to the i-bit to enable nested inter- rupts. all enabled interrupts can then interrupt the current interrupt routine. the i-bit is automatically set when a return from interrupt instruction ? reti ? is executed. there are basically two types of interrupts. the first type is triggered by an event that sets the interrupt flag. for these interrupts, the program counter is vectored to the actual interrupt vector in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt flag. interr upt flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. if an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt flag will be set and remem- bered until the interrupt is enabled, or the flag is cleared by software. similarly, if one or more interrupt conditions occur while the global interrupt enable bit is cleared, the cor- responding interrupt fl ag(s) will be set and remembered until the global interrupt enable bit is set, and will then be exec uted by order of priority. the second type of interrupts will trigger as long as the interrupt condition is present. these interrupts do not necessarily have interrup t flags. if the interrupt condition disap- pears before the interrupt is enabled , the interrupt will not be triggered. when the avr exits from an in terrupt, it will always return to the main pr ogram and exe- cute one more instruction before any pending interrupt is served. note that the status register is not automatically stored when entering an interrupt rou- tine, nor restored when returning from an interrupt routine. this must be handled by software. when using the cli instruction to disable in terrupts, the interrupts will be immediately disabled. no interrupt will be exec uted after the cli instruction, even if it occurs simulta- total execution time register operands fetch alu operation execute result write back t1 t2 t3 t4 clk cpu
12 attiny2313/v 2543f?avr?08/04 neously with the cli instruction. the following example shows how this can be used to avoid interrupts during the timed eeprom write sequence.. when using the sei instructio n to enable interrupts, the in struction following sei will be executed before any pending interrupts, as shown in this example. interrupt response time the interrupt execution response for all the enabled avr interrupts is four clock cycles minimum. after four clock cycles the program vector address for the actual interrupt handling routine is executed. during this four clock cycle period, the program counter is pushed onto the stack. the vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. if an interr upt occurs during execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. if an interrupt occurs when the mcu is in sleep mode, the interrupt execution response time is increased by four clock cycles. this increase comes in addition to the start-up time from the selected sleep mode. a return from an interrupt handling routine ta kes four clock cycles. during these four clock cycles, the program counter (two bytes) is popped back from the stack, the stack pointer is incremented by two, and the i-bit in sreg is set. assembly code example in r16, sreg ; store sreg value cli ; disable interrupts during timed sequence sbi eecr, eempe ; start eeprom write sbi eecr, eepe out sreg, r16 ; restore sreg value (i-bit) c code example char csreg; csreg = sreg; /* store sreg value */ /* disable interrupts during timed sequence */ __disable_interrupt(); eecr |= (1< 13 attiny2313/v 2543f?avr?08/04 avr attiny2313 memories this section describes the different memori es in the attiny2313. the avr architecture has two main memory spaces, the data memory and the program memory space. in addition, the attiny2 313 features an eeprom memory for data st orage. all three mem- ory spaces are linear and regular. in-system reprogrammable flash program memory the attiny2313 contains 2k bytes on-chi p in-system reprogrammable flash memory for program storage. since all avr instructions are 16 or 32 bits wide, the flash is orga- nized as 1k x 16. the flash memory has an endurance of at least 10,000 write/erase cycles. the attiny2313 program counter (pc) is 10 bits wide, thus addressing the 1k program memory locations. ?memory programming? on page 157 contains a detailed description on flash data serial downloading using the spi pins. constant tables can be allocated within th e entire program memory address space (see the lpm ? load program memory instruction description). timing diagrams for instruction fetch and exec ution are presented in ?instruction execu- tion timing? on page 10. figure 8. program memory map 0x0000 0x03f f program memory
14 attiny2313/v 2543f?avr?08/04 sram data memory figure 9 shows how the attiny2313 sram memory is organized. the lower 224 data memory locations address both the register file, the i/o memory, extended i/o memory, and the internal data sram. the first 32 locations address the register file, the next 64 location the standard i/o memory, and the next 128 locations address the internal data sram. the five different addressing modes for the data memory cover: direct, indirect with dis- placement, indirect, indirect with pre-decrement, and indirect with post-increment. in the register file, registers r26 to r31 feature the indirect addressing pointer registers. the direct addressing reaches the entire data space. the indirect with displacement mode reaches 63 address locations from the base address given by the y- or z-register. when using register indirect addressing modes with automatic pre-decrement and post- increment, the address registers x, y, and z are decremented or incremented. the 32 general purpose working registers, 64 i/o registers, and the 128 bytes of inter- nal data sram in the attiny2313 are all accessible through all these addressing modes. the register file is described in ?general purpose register file? on page 8. figure 9. data memory map data memory access times this section describes the general access ti ming concepts for internal memory access. the internal data sram access is performed in two clk cpu cycles as described in figure 10. 32 registers 64 i/o registers internal sram (128 x 8) 0x0000 - 0x001f 0x0020 - 0x005f 0x00df 0x0060 data memory
15 attiny2313/v 2543f?avr?08/04 figure 10. on-chip data sram access cycles eeprom data memory the attiny2313 contains 128 bytes of data eeprom memory. it is organized as a sep- arate data space, in which single bytes can be read and written. the eeprom has an endurance of at least 100,000 write/erase cycles. the access between the eeprom and the cpu is described in the following, specifying the eeprom address registers, the eeprom data register, and the eeprom control register. fo r a detailed descrip- tion of serial data downloading to the eeprom, see page 171. eeprom read/write access the eeprom access registers are accessible in the i/o space. the write access time for the eeprom is given in table 1. a self-timing function, how- ever, lets the user software detect when t he next byte can be written. if the user code contains instructions that write the eepr om, some precautions must be taken. in heavily filtered power supplies, v cc is likely to rise or fall slowly on power-up/down. this causes the device for some period of time to run at a voltage lower than specified as minimum for the clock frequency used. see ?preventing eeprom corruption? on page 19. for details on how to avoid problems in these situations. in order to prevent unintentional eeprom writes, a specific write procedure must be fol- lowed. refer to the descripti on of the eeprom control regi ster for details on this. when the eeprom is read, the cpu is halt ed for four clock cycles before the next instruction is executed. when the eeprom is written, the cpu is halted for two clock cycles before the next instruction is executed. the eeprom address register  bit 7 ? res: reserved bit this bit is reserved in the attiny 2313 and will always read as zero. clk wr rd data data address address valid t1 t2 t3 compute address read write cpu memory access instruction next instruction bit 76543210 ? eear6 eear5 eear4 eear3 eear2 eear1 eear0 eear read/write r r/w r/w r/w r/w r/w r/w r/w initial value 0 x x x x x x x
16 attiny2313/v 2543f?avr?08/04  bits 6..0 ? eear6..0: eeprom address the eeprom address register ? eear specif y the eeprom address in the 128 bytes eeprom space. the eeprom data bytes are addressed linearly between 0 and 127. the initial value of eear is undefined. a proper value must be written before the eeprom may be accessed. the eeprom data register ? eedr  bits 7..0 ? eedr7..0: eeprom data for the eeprom write operation, the eedr register contains the data to be written to the eeprom in the address gi ven by the eear register. for the eeprom read oper- ation, the eedr contains the data read out from the eeprom at the address given by eear. the eeprom control register ? eecr  bits 7..6 ? res: reserved bits these bits are reserved bits in the attiny2313 and will a lways read as zero.  bits 5, 4 ? eepm1 and eepm0: eeprom programming mode bits the eeprom programming mode bits setting defines which programming action that will be triggered when writing eepe. it is possible to program data in one atomic opera- tion (erase the old value and program the new value) or to split the erase and write operations in two different operations. the programming times for the different modes are shown in table 1. while eepe is set, any write to eepmn will be ignored. during reset, the eepmn bits will be reset to 0b00 unless the eeprom is busy programming.  bit 3 ? eerie: eeprom ready interrupt enable writing eerie to one enables the eeprom ready interrupt if the i-bit in sreg is set. writing eerie to zero disabl es the interrupt. the eeprom ready inte rrupt generates a constant interrupt when non-volatile memory is ready for programming. bit 76543210 msb lsb eedr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ? ? eepm1 eepm0 eerie eempe eepe eere eecr read/write r r r/w r/w r/w r/w r/w r/w initial value 0 0 x x 0 0 x 0 table 1. eeprom mode bits eepm1 eepm0 programming time operation 0 0 3.4 ms erase and write in one operation (atomic operation) 0 1 1.8 ms erase only 1 0 1.8 ms write only 1 1 ? reserved for future use
17 attiny2313/v 2543f?avr?08/04  bit 2 ? eempe: eeprom master program enable the eempe bit determines whether writing eepe to o ne will have effect or not. when eempe is set, setting eepe within four clock cycles will program the eeprom at the selected address. if eempe is zero, setting eepe w ill have no effect. when eempe has been written to one by software, hardware clears the bit to zero after four clock cycles.  bit 1 ? eepe: eeprom program enable the eeprom program enable signal eepe is the programming enable signal to the eeprom. when eepe is written, the eeprom will be programmed according to the eepmn bits setting. the eempe bit must be written to one before a logical one is writ- ten to eepe, otherwise no eeprom write takes place. when th e write access time has elapsed, the eepe bit is cleared by ha rdware. when eepe has been set, the cpu is halted for two cycles before the next instruction is executed.  bit 0 ? eere: eeprom read enable the eeprom read enable signal ? eere ? is the read strobe to the eeprom. when the correct address is set up in the eear register, the eere bit must be written to one to trigger the eeprom read. the eeprom read access takes one in struction, and the requested data is available immediately. when the eeprom is read, the cpu is halted for four cycles before the nex t instruction is executed. th e user should poll the eepe bit before starting the read operation. if a write operation is in progress, it is neither possible to read the eeprom, nor to change the eear register. atomic byte programming using atomic byte programming is the simp lest mode. when writing a byte to the eeprom, the user must write the address in to the eear register and data into eedr register. if the eepmn bits are zero, writi ng eepe (within four cycles after eempe is written) will trigger the erase/ write operation. both the er ase and write cyc le are done in one operation and the total programming time is given in table 1. the eepe bit remains set until the erase and write operations are completed. while the device is busy with programming, it is not possible to do any ot her eeprom operations. split byte programming it is possible to split the erase and write cycle in two diff erent operations. this may be useful if the system requires short access time for some limited period of time (typically if the power supply voltage falls). in order to take advantage of this method, it is required that the locations to be written have been erased before the write operation. but since the erase and write operations are split, it is possible to do the erase operations when the system allows doing time-consuming operations (typically after power-up). erase to erase a byte, the address mu st be written to eear. if th e eepmn bits are 0b01, writ- ing the eepe (within four cycle s after eempe is written) will trigger the er ase operation only (programming time is given in table 1). the eepe bit remains set until the erase operation completes. while the device is busy programming, it is not possible to do any other eeprom operations. write to write a location, the user must write the address into eear and the data into eedr. if the eepmn bits are 0b10, writing the eepe (w ithin four cycles after eempe is written) will trigger the write operation only (programming time is gi ven in table 1). the eepe bit remains set until the write operation completes. if the location to be written has not been erased before write, the data that is stored must be considered as lost. while the device is busy with programming , it is not possible to do any other eeprom operations.
18 attiny2313/v 2543f?avr?08/04 the calibrated oscillator is us ed to time the eeprom accesse s. make sure the oscilla- tor frequency is within the requirements desc ribed in ?oscillator calibration register ? osccal? on page 25. the following code examples show one assembly and one c function for writing to the eeprom. the examples assume that interrupts are controlled (e.g. by disabling inter- rupts globally) so that no interrupts will occur during executio n of these functions. assembly code example eeprom_write: ; wait for completion of previous write sbic eecr,eepe rjmp eeprom_write ; set up address (r17) in address register out eear, r17 ; write data (r16) to data register out eedr,r16 ; write logical one to eempe sbi eecr,eempe ; start eeprom write by setting eepe sbi eecr,eepe ret c code example void eeprom_write( unsigned int uiaddress, unsigned char ucdata) { /* wait for completion of previous write */ while(eecr & (1< 19 attiny2313/v 2543f?avr?08/04 the next code examples show assembly an d c functions for reading the eeprom. the examples assume that interr upts are controlled so that no interrupts will occur during execution of these functions. preventing eeprom corruption during periods of low v cc, the eeprom data can be corrupt ed because the supply volt- age is too low for the cpu and the eeprom to operate prope rly. these issues are the same as for board level sys tems using eeprom, and the sa me design solutions should be applied. an eeprom data corruption can be caused by two situations when the voltage is too low. first, a regular write sequence to the eeprom requires a minimum voltage to operate correctly. secondly, the cpu itself ca n execute instructions incorrectly, if the supply voltage is too low. eeprom data corruption can easily be avoided by following this design recommendation: keep the avr reset active (low) during pe riods of insufficient power supply voltage. this can be done by enabling the internal brown-out detector (bod). if the detection level of the internal bod does not match the needed detection level, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write op eration will be complete d provided that the power supply voltage is sufficient. assembly code example eeprom_read: ; wait for completion of previous write sbic eecr,eewe rjmp eeprom_read ; set up address (r17) in address register out eear, r17 ; start eeprom read by writing eere sbi eecr,eere ; read data from data register in r16,eedr ret c code example unsigned char eeprom_read( unsigned int uiaddress) { /* wait for completion of previous write */ while(eecr & (1< 20 attiny2313/v 2543f?avr?08/04 i/o memory the i/o space definition of the attiny2313 is shown in ?register summary? on page 209. all attiny2313 i/os and peripherals are placed in the i/o space. all i/o locations may be accessed by the ld/lds/ldd and st/sts/std instructions, transferring data between the 32 general purpose working registers and the i/o space. i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using the sbi and cbi instruc- tions. in these registers, the value of single bits can be checked by using the sbis and sbic instructions. refer to the instruction set section for more details. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instructions, 0x20 must be added to these addresses. for compatibility with futu re devices, reserved bits should be written to ze ro if accessed. reserved i/o memory addresses should never be written. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avrs, the cbi and sbi instructions will only oper ate on the specified bit, and can therefore be used on registers containing such status flags. the cbi and sbi instructions work with registers 0x00 to 0x1f only. the i/o and peripherals control registers are explained in later sections. general purpose i/o registers the attiny2313 contains three general purpos e i/o registers. these registers can be used for storing any information, and they are particularly useful for storing global vari- ables and status flags. general purpose i/o registers within the address range 0x00 - 0x1f are directly bit-accessible using the sbi, cbi, sbis, and sbic instructions. general purpose i/o register 2 ? gpior2 general purpose i/o register 1 ? gpior1 general purpose i/o register 0 ? gpior0 bit 76543210 msb lsb gpior2 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 msb lsb gpior1 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 msb lsb gpior0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
21 attiny2313/v 2543f?avr?08/04 system clock and clock options clock systems and their distribution figure 11 presents the principal clock system s in the avr and their distribution. all of the clocks need not be active at a given time. in order to reduce power consumption, the clocks to modules not being used can be halted by using differ ent sleep modes, as described in ?power management and sleep modes? on page 29. the clock systems are detailed below. figure 11. clock distribution cpu clock ? clk cpu the cpu clock is routed to parts of the system concerned with operation of the avr core. examples of such modules are the general purpose register file, the status reg- ister and the data memory holding the stack pointer. halting the cpu clock inhibits the core from performing general operations and calculations. i/o clock ? clk i/o the i/o clock is used by the majority of the i/o modules, like timer/counters, and usart. the i/o clock is also used by the external interrupt module, but note that some external interrupts are detected by asynchronous logic, allowing such interrupts to be detected even if the i/o clock is halted. also note that start condition detection in the usi module is carried out asynchronously when clk i/o is halted, enabling usi start condition detection in all sleep modes. flash clock ? clk flash the flash clock controls operation of the fl ash interface. the flash clock is usually active simultaneously with the cpu clock. general i/o modules cpu core ram clk i/o avr clock control unit clk cpu flash and eeprom clk flash source clock watchdog timer watchdog oscillator reset logic clock multiplexer watchdog clock calibrated rc oscillator crystal oscillator external clock
22 attiny2313/v 2543f?avr?08/04 clock sources the device has the following clock source options, selectable by flash fuse bits as shown below. the clock from the selected source is input to the avr clock generator, and routed to the appropriate modules. note: 1. for all fuses ?1? means unprogrammed while ?0? means programmed. the various choices for each clocking option is given in the followi ng sections. when the cpu wakes up from power-down, the selected clock source is used to time the start-up, ensuring stable oscillator operation before in struction execution starts. when the cpu starts from reset, there is an additional dela y allowing the power to reach a stable level before commencing normal operation. the wa tchdog oscillator is used for timing this real-time part of the start-up time. the number of wdt oscillator cycles used for each time-out is shown in tabl e 3. the frequency of the watchdog oscilla tor is voltage dependent as shown in ?attiny2313 typical characteristics? on page 179. default clock source the device is shipped with cksel = ?0010?, sut = ?10?, and ckdiv8 programmed. the default clock source setting is the inte rnal rc oscillator with longest start-up time and an initial system clock prescaling of 8. this default setting ensures that all users can make their desired clock source setting using an in-system or parallel programmer. crystal oscillator xtal1 and xtal2 are input and output, respectively, of an inverting amplifier which can be configured for use as an on-chip oscillator, as shown in figure 12 on page 23. either a quartz crystal or a ceramic resonator may be used. c1 and c2 should always be equal for both crystals and resonators. the optimal value of the capacitors depends on the crystal or resonator in use, the amount of stray capac- itance, and the electromagnetic noise of the environment. some initial guidelines for choosing capacitors for use with crystals are given in table 4 on page 23. for ceramic resonators, the capacitor values given by the manufacturer should be used. table 2. device clocking select (1) device clocking option cksel3..0 external clock 0000 calibrated internal rc oscillator 4mhz 0010 calibrated internal rc oscillator 8mhz 0100 watchdog oscillator 128khz 0110 external crystal/ceramic resonator 1000 - 1111 reserved 0001/0011/0101/0111 table 3. number of watchdog oscillator cycles typ time-out (v cc = 5.0v) typ time-out (v cc = 3.0v) number of cycles 4.1 ms 4.3 ms 4k (4,096) 65 ms 69 ms 64k (65,536)
23 attiny2313/v 2543f?avr?08/04 figure 12. crystal oscillator connections the oscillator can operate in three different modes, each optimized for a specific fre- quency range. the operating mode is selected by the fuses cksel3..1 as shown in table 4. notes: 1. the frequency ranges are preliminary values. actual values are tbd. 2. this option should not be used with crystals, only with ceramic resonators. the cksel0 fuse together with the sut1..0 fuses select the start-up times as shown in table 5. table 4. crystal oscillator operating modes cksel3..1 frequency range (1) (mhz) recommended range for capacitors c1 and c2 for use with crystals (pf) 100 (2) 0.4 - 0.9 ? 101 0.9 - 3.0 12 - 22 110 3.0 - 8.0 12 - 22 111 8.0 - 12 - 22 xtal2 xtal1 gnd c2 c1
24 attiny2313/v 2543f?avr?08/04 notes: 1. these options should only be used wh en not operating close to the maximum fre- quency of the device, and only if frequency stabili ty at start-up is not important for the application. these options ar e not suitable for crystals. 2. these options are intended for use with ceramic resonators and will ensure fre- quency stability at start-up. they can also be used with crystals when not operating close to the maximum frequency of the device, and if frequency stability at start-up is not important for the application. calibrated internal rc oscillator the calibrated inte rnal rc oscillator provides a fixe d 8.0 mhz clock. the frequency is nominal value at 3v and 25 c. if 8 mhz frequency exceed s the specification of the device (depends on v cc ), the ckdiv8 fuse must be programmed in order to divide the internal frequency by 8 during start-up. the device is shipped with the ckdiv8 fuse programmed. this clock may be selected as the system clock by programming the cksel fuses as shown in tabl e 6. if selected, it will oper ate with no external compo- nents. during reset, hardware loads the calibration byte into the osccal register and thereby automatically calibrates the rc oscillator. at 3v and 25 c, this calibration gives a frequency within 10% of the nominal frequency. using calibration methods as described in application notes available at www.atmel.com/avr it is possible to achieve 2% accuracy at any given v cc and temperature. when this oscillator is used as the chip clock, the watchdog oscillator will still be used for the watchdog timer and for the reset time-out. for more information on the pre-programmed calibration value, see the section ?calibration byte? on page 159. note: 1. the device is shipped with this option selected. table 5. start-up times for the crystal oscillator clock selection cksel0 sut1..0 start-up time from power-down and power-save additional delay from reset (v cc = 5.0v) recommended usage 0 00 258 ck (1) 14ck + 4.1 ms ceramic resonator, fast rising power 0 01 258 ck (1) 14ck + 65 ms ceramic resonator, slowly rising power 010 1k ck (2) 14ck ceramic resonator, bod enabled 011 1k ck (2) 14ck + 4.1 ms ceramic resonator, fast rising power 100 1k ck (2) 14ck + 65 ms ceramic resonator, slowly rising power 1 01 16k ck 14ck crystal oscillator, bod enabled 1 10 16k ck 14ck + 4.1 ms crystal oscillator, fast rising power 1 11 16k ck 14ck + 65 ms crystal oscillator, slowly rising power table 6. internal calibrated rc o scillator operating modes cksel3..0 nominal frequency 0010 - 0011 4.0 mhz (1) 0100 - 0101 8.0 mhz
25 attiny2313/v 2543f?avr?08/04 when this oscillator is selected, start-up times are determined by the sut fuses as shown in table 7. note: 1. the device is shipped with this option selected. oscillator calibration register ? osccal  bits 6..0 ? cal6..0: oscillator calibration value writing the calibration byte to this address will trim the inte rnal oscillator to remove pro- cess variations from the oscillator frequency. this is done automatically during chip reset. when osccal is zero, the lowest available frequency is chosen. writing non- zero values to this register will increase the frequency of the internal oscillator. writing 0x7f to the register gives the highest avai lable frequency. the calibrated oscillator is used to time eeprom and flash access. if eeprom or flash is written, do not cali- brate to more than 10% above the nominal fr equency. otherwise, the eeprom or flash write may fail. note that the oscillator is in tended for calib ration to 8.0/4.0 mhz. tuning to other values is not guaranteed, as indicated in table 8. avoid changing the calibration value in large steps when calibrating the calibrated inter- nal rc oscillator to ensure stable operation of the mcu. a variation in frequency of more than 2% from one cycle to the next c an lead to unpredictable behavior. changes in osccal should not exceed 0x20 for each calibration. table 7. start-up times for the internal calib rated rc oscillator clock selection sut1..0 start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) recommended usage 00 6 ck 14ck bod enabled 01 6 ck 14ck + 4.1 ms fast rising power 10 (1) 6 ck 14ck + 65 ms slowly rising power 11 reserved bit 76543210 ? cal6 cal5 cal4 cal3 cal2 cal1 cal0 osccal read/write r r/w r/w r/w r/w r/w r/w r/w initial value device spec ific calibration value table 8. internal rc oscilla tor frequency range. osccal value min frequency in percentage of nominal frequency max frequency in percentage of nominal frequency 0x00 50% 100% 0x3f 75% 150% 0x7f 100% 200%
26 attiny2313/v 2543f?avr?08/04 external clock to drive the device from an external clock source, xtal1 should be driven as shown in figure 13. to run the device on an extern al clock, the cksel fuses must be pro- grammed to ?0000?. figure 13. external clock drive configuration when this clock source is selected, start- up times are determined by the sut fuses as shown in table 10. when applying an external clock, it is required to avoid sudden changes in the applied clock frequency to ensure stable operation of the mcu. a variation in frequency of more than 2% from one clock cycle to the next can lead to unpredictable behavior. it is required to ensure that the mcu is kept in reset during such changes in the clock frequency. note that the system clock prescaler can be used to implement run-time changes of the internal clock frequency while still ensuring stable operation. table 9. crystal oscillator clock frequency cksel3..0 frequency range 0000 - 0001 0 - 16 mhz table 10. start-up times for the external clock selection sut1..0 start-up time from power- down and power-save additional delay from reset (v cc = 5.0v) recommended usage 00 6 ck 14ck bod enabled 01 6 ck 14ck + 4.1 ms fast rising power 10 6 ck 14ck + 65 ms slowly rising power 11 reserved nc external clock signal xtal2 xtal1 gnd
27 attiny2313/v 2543f?avr?08/04 128 khz internal oscillator the 128 khz internal oscillator is a low power oscillator providing a clock of 128 khz. the frequency is nominal at 3 v and 25 c. this clock may be selected as the system clock by programming the c ksel fuses to ?0110 - 0111?. when this clock source is selected, start- up times are determined by the sut fuses as shown in table 11. clock prescale register ? clkpr  bit 7 ? clkpce: clock prescaler change enable the clkpce bit must be written to logic one to enable change of the clkps bits. the clkpce bit is only updated when the other bi ts in clkpr are simu ltaneously written to zero. clkpce is cleared by hardware four cycl es after it is written or when clkps bits are written. rewriting the clkpce bit within th is time-out period does neither extend the time-out period, nor clear the clkpce bit.  bits 3..0 ? clkps3..0: clock prescaler select bits 3 - 0 these bits define the division factor between the selected clock source and the internal system clock. these bits can be written run- time to vary the clock frequency to suit the application requirements. as t he divider divides the master clock input to the mcu, the speed of all synchronous peripherals is reduce d when a division factor is used. the divi- sion factors are given in table 12. to avoid unintentional changes of clock frequency, a special write procedure must be followed to chang e the clkps bits: 1. write the clock prescaler change enable (clkpce) bit to one and all other bits in clkpr to zero. 2. within four cycles, write the desire d value to clkps while writing a zero to clkpce. interrupts must be disabled when changing prescaler setting to make sure the write pro- cedure is not interrupted. the ckdiv8 fuse determines the initial value of the clkps bits. if ckdiv8 is unpro- grammed, the clkps bits will be reset to ?0000?. if ckdiv8 is programmed, clkps bits are reset to ?0011?, giving a division factor of 8 at start up. this feature should be used if the selected clock source has a higher frequency than the maximum frequency of the device at the present operating conditions. note that any value can be written to the clkps bits regardless of the ckdiv8 fuse setting. the application software must ensure that a sufficient division factor is ch osen if the selected clock source has a higher table 11. start-up times for the 1 28 khz internal oscillator sut1..0 start-up time from power- down and power-save additional delay from reset recommended usage 00 6 ck 14ck bod enabled 01 6 ck 14ck + 4 ms fast rising power 10 6 ck 14ck + 64 ms slowly rising power 11 reserved bit 76543210 clkpce ? ? ? clkps3 clkps2 clkps1 clkps0 clkpr read/write r/w r r r r/w r/w r/w r/w initial value 0 0 0 0 see bit description
28 attiny2313/v 2543f?avr?08/04 frequency than the maximum frequency of th e device at the present operating condi- tions. the device is shipped with the ckdiv8 fuse programmed. table 12. clock prescaler select clkps3 clkps2 clkps1 clkps0 clock division factor 0000 1 0001 2 0010 4 0011 8 0100 16 0101 32 0110 64 0111 128 1000 256 1001 reserved 1010 reserved 1011 reserved 1100 reserved 1101 reserved 1110 reserved 1111 reserved
29 attiny2313/v 2543f?avr?08/04 power management and sleep modes sleep modes enable the application to shut down unused modules in the mcu, thereby saving power. the avr provides various sleep modes allowing the user to tailor the power consumption to the application?s requirements. to enter any of the three sleep modes, the se bit in smcr must be written to logic one and a sleep instruction must be executed. the sm1 and sm0 bits in the mcucr reg- ister select which sleep mode (idle, power-down, or standby) will be activated by the sleep instruction. see table 13 for a summary. if an enabled interr upt occurs while the mcu is in a sleep mode, the mcu wakes up. the mcu is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction following sleep. the contents of the register file and sram are unal- tered when the device wakes up from sleep. if a reset occurs during sleep mode, the mcu wakes up and executes from the reset vector. figure 11 on page 21 presents the different clock systems in the attiny2313, and their distribution. the figure is helpful in selecting an appropriate sleep mode. mcu control register ? mcucr the sleep mode control register contains control bits for power management.  bits 6, 4 ? sm1..0: sleep mode select bits 1 and 0 these bits select between the five available sleep modes as shown in table 13. note: 1. standby mode is only recommended for use with external crystals or resonators.  bit 5 ? se: sleep enable the se bit must be written to logic one to make the mcu enter the sleep mode when the sleep instruction is executed. to avoid the mcu entering the sleep mode unless it is the programmer?s purpose, it is recommended to write the sleep enable (se) bit to one just before the execution of the sleep instruction and to cl ear it immediately after wak- ing up. idle mode when the sm1..0 bits are written to 00, the sleep instructio n makes the mcu enter idle mode, stopping the cpu but allowing the uart, analog comparator, adc, usi, timer/counters, watchdog, and the interrupt system to continue operating. this sleep mode basically halts clk cpu and clk flash , while allowing the ot her clocks to run. idle mode enables the mcu to wake up fr om external triggered interrupts as well as internal ones like the timer overflow and uart transmit complete interrupts. if wake- up from the analog comparator interrupt is not required, the analog comparator can be powered down by setting the acd bit in the analog comparator control and status register ? acsr. this will reduce po wer consumption in idle mode. bit 76543210 pud sm1 se sm0 isc11 isc10 isc01 isc00 mcucr read/write r r/w r/w r/w r/w r/w r/w r/w initial value00000000 table 13. sleep mode select sm1 sm0 sleep mode 00idle 0 1 power-down 1 1 power-down 1 0 standby
30 attiny2313/v 2543f?avr?08/04 power-down mode when the sm1..0 bits are written to 01 or 11, the sleep instru ction make s the mcu enter power-down mode. in th is mode, the external osc illator is stopped, while the external interrupts, the usi start condition detection, and the watchdog continue operat- ing (if enabled). only an external reset, a watchdog reset, a brown-out reset, usi start condition interrupt, an external level interrupt on int0, or a pin change interrupt can wake up the mcu. this sleep mode basically halts all generated clocks, allowing opera- tion of asynchronous modules only. note that if a level triggered interrupt is used for wake-up from power-down mode, the changed level must be held for some time to wake up the mcu. refer to ?external inter- rupts? on page 58 for details. when waking up from power-down mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. this allows the clock to restart and become stable after having been stopped. the wake-up period is defined by the same cksel fuses that define the reset time-out period, as described in ?clock sources? on page 22. standby mode when the sm1..0 bits are 10 and an external crystal/resonator clock option is selected, the sleep instruction makes the mcu enter standby mode. this mode is identical to power-down with the exception that the oscillator is kept running. from standby mode, the device wakes up in six clock cycles. notes: 1. only recommended with external crystal or resonator selected as clock source. 2. for int0, only level interrupt. minimizing power consumption there are several issues to consider when trying to minimize the power consumption in an avr controlled system. in general, sleep modes should be used as much as possi- ble, and the sleep mode should be selected so that as few as pos sible of the device?s functions are operating. all functions not needed should be disabled. in particular, the following modules may need special consider ation when trying to achieve the lowest possible power consumption. analog comparator when entering idle mode, the analog comparator should be disabled if not used. in other sleep modes, the analog comparator is automatically disabled. however, if the analog comparator is set up to use the internal voltage reference as input, the analog comparator should be disabled in all sleep modes. otherwise, the internal voltage ref- erence will be enabled, independent of sleep mode. refer to ?analog comparator? on page 148 for details on how to configure the analog comparator. table 14. active clock domains and wake-up sources in the different sleep modes. active clock domains oscillators wake-up sources sleep mode clk cpu clk flash clk io enabled int0, int1 and pin change usi start condition spm/eeprom ready other i/o idle x x xxxx power-down x (2) x standby (1) xx (2) x
31 attiny2313/v 2543f?avr?08/04 brown-out detector if the brown-out detector is not needed by the application, this module should be turned off. if the brown-out detector is enabled by the bodlevel fuses, it will be enabled in all sleep modes, and hence, always consume power. in the deeper sleep modes, this will contribute significantly to the total curr ent consumption. refer to ?brown-out detec- tion? on page 34 for details on how to configure the brown-out detector. internal voltage reference the internal voltage reference will be enabled when needed by the brown-out detec- tion or the analog comparator. if these modules are disabled as described in the sections above, the internal vo ltage reference will be disabled and it will not be consum- ing power. when turned on again, the user must allow the reference to start up before the output is used. if the reference is kept on in sleep mode, the output can be used immediately. refer to ?internal voltage reference? on page 37 for details on the start-up time. watchdog timer if the watchdog timer is not needed in the application, the module should be turned off. if the watchdog timer is enabled, it will be enabled in all sleep modes, and hence, always consume power. in the deeper sleep modes, this will contribute significantly to the total current consumption. refer to ?interrupts? on page 43 for details on how to con- figure the watchdog timer. port pins when entering a sleep mode, all port pins should be configured to use minimum power. the most important is then to ensure that no pins drive resistive loads. in sleep modes where the i/o clock (clk i/o ) is stopped, the input buffers of the device will be disabled. this ensures that no power is consumed by the input logic when not needed. in some cases, the input logic is needed for dete cting wake-up conditio ns, and it will then be enabled. refer to the section ?digital input enable and sleep modes? on page 49 for details on which pins are enabled. if the input buffer is enabled and the input signal is left floating or have an analog signal level close to v cc /2, the input buffer will use exces- sive power. for analog input pins, the digital input buffe r should be disabled at all times. an analog signal level close to v cc /2 on an input pin can cause signi ficant current even in active mode. digital input buffers can be disabled by writing to the digital input disable regis- ters (didr). refer to ?digital input disable register ? didr? on page 149.
32 attiny2313/v 2543f?avr?08/04 system control and reset resetting the avr during reset, all i/o registers are set to their initial values, and the program starts exe- cution from the reset vector. the instruction placed at the reset vector must be an rjmp ? relative jump ? instruction to the reset handling routine. if the program never enables an interrupt source, the interrupt vectors are not used, and regular program code can be placed at these locations. the circuit diagram in figure 14 shows the reset logic. table 15 defines the electrical parameters of the reset circuitry. the i/o ports of the avr are immediately reset to their initial state when a reset source goes active. this does not require any clock source to be running. after all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. this allows the power to reach a stable level before normal operation starts. the time-out period of the delay count er is defined by the user through the sut and cksel fuses. the different selections for the delay period are presented in ?clock sources? on page 22. reset sources the attiny2313 has four sources of reset:  power-on reset. the mcu is reset when the supply voltage is below the power-on reset threshold (v pot ).  external reset. the mcu is reset when a low level is present on the reset pin for longer than the minimum pulse length.  watchdog reset. the mcu is reset when the watchdog timer period expires, the watchdog is enabled, and watchdog interrupt is disabled.  brown-out reset. the mcu is reset when the supply voltage v cc is below the brown-out reset threshold (v bot ) and the brown-out detector is enabled. figure 14. reset logic mcu status register (mcusr) brown-out reset circuit bodlevel [2..0] delay counters cksel[3:0] ck timeout wdrf borf extrf porf data bus clock generator spike filter pull-up resistor watchdog oscillator sut [ 1:0 ] power-on reset circuit
33 attiny2313/v 2543f?avr?08/04 notes: 1. values are guidelines only. actual values are tbd. 2. the power-on reset will not work unless the supply voltage has been below v pot (falling) power-on reset a power-on reset (por) pulse is generated by an on-chip detection circuit. the detec- tion level is defined in table 15. the por is activated whenever v cc is below the detection level. the por circuit can be used to trigger the start-up reset, as well as to detect a failure in supply voltage. a power-on reset (por) circuit ensures that the device is reset from power-on. reach- ing the power-on reset threshold voltage invokes the delay counter, which determines how long the device is kept in reset after v cc rise. the reset signal is activated again, without any delay, when v cc decreases below t he detection level. figure 15. mcu start-up, reset tied to v cc table 15. reset characteristics symbol parameter condition min (1) typ (1) max (1) units v pot power-on reset threshold voltage (rising) t a = -40 - 85 c1.2 v power-on reset threshold voltage (falling) (2) t a = -40 - 85 c1.1 v v rst reset pin threshold voltage v cc = 1.8 - 5.5v 0.1 v cc 0.9 v cc v t rst minimum pulse width on reset pin v cc = 1.8 - 5.5v 2.5 s v reset time-out internal reset t tout v pot v rst cc
34 attiny2313/v 2543f?avr?08/04 figure 16. mcu start-up, reset extended externally external reset an external reset is generated by a low level on the reset pin. reset pulses longer than the minimum pulse width (see table 15) will generate a reset, even if the clock is not running. shorter pulses are not guaranteed to generate a reset. when the applied signal reaches the reset threshold voltage ? v rst ? on its positive edge, the delay counter starts the mcu after the time-out period ? t tout ? has expired. figure 17. external reset during operation brown-out detection attiny2313 has an on-chip brown-out detection (bod) circuit for monitoring the v cc level during operation by comparing it to a fi xed trigger level. the trigger level for the bod can be selected by the bodlevel fuses. the trigger level has a hysteresis to ensure spike free brown-out detection. the hysteresis on the detection level should be interpreted as v bot+ = v bot + v hyst /2 and v bot- = v bot - v hyst /2. reset time-out internal reset t tout v pot v rst v cc cc table 16. bodlevel fuse coding (1) bodlevel 2..0 fuses min v bot typ v bot max v bot units 111 bod disabled 110 1.8 v 101 2.7 100 4.3
35 attiny2313/v 2543f?avr?08/04 note: 1. v bot may be below nominal minimum operating voltage for some devices. for devices where this is the case, t he device is tested down to v cc = v bot during the production test. this guar antees that a brown-out reset will occur before v cc drops to a voltage where correct operation of the microcontroller is no longer guaranteed. the test is performed using bodlevel = 110 for attiny2313v and bodlevel = 101 for attiny2313l. when the bod is enabled, and v cc decreases to a value below the trigger level (v bot- in figure 18), the brown-out reset is immediately activated. when v cc increases above the trigger level (v bot+ in figure 18), the delay counter starts the mcu after the time- out period t tout has expired. the bod circuit will only detect a drop in v cc if the voltage stays below the trigger level for longer than t bod given in table 15. figure 18. brown-out reset during operation 011 reserved 010 001 000 table 17. brown-out characteristics symbol parameter min typ max units v hyst brown-out detector hysteresis 50 mv t bod min pulse width on brown-out reset 2 ns table 16. bodlevel fuse coding (1) bodlevel 2..0 fuses min v bot typ v bot max v bot units v cc reset time-out internal reset v bot- v bot+ t tout
36 attiny2313/v 2543f?avr?08/04 watchdog reset when the watchdog times out, it will generate a short rese t pulse of one ck cycle dura- tion. on the falling edge of this pulse, the delay timer starts counting the time-out period t tout . refer to page 43 for details on operation of the watchdog timer. figure 19. watchdog reset during operation mcu status register ? mcusr the mcu status register provides information on which reset source caused an mcu reset.  bit 3 ? wdrf: watchdog reset flag this bit is set if a watchdog reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag.  bit 2 ? borf: brown-out reset flag this bit is set if a brown-out reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag.  bit 1 ? extrf: external reset flag this bit is set if an external reset occurs. the bit is reset by a power-on reset, or by writing a logic zero to the flag.  bit 0 ? porf: power-on reset flag this bit is set if a power-on reset occurs. th e bit is reset only by writing a logic zero to the flag. to make use of the reset flags to identif y a reset condition, the user should read and then reset the mcusr as early as possible in the program. if the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags. ck cc bit 76543210 ? ? ? ? wdrf borf extrf porf mcusr read/write r r r r r/w r/w r/w r/w initial value 0 0 0 see bit description
37 attiny2313/v 2543f?avr?08/04 internal voltage reference attiny2313 features an internal bandgap refer ence. this reference is used for brown- out detection, and it can be used as an input to the analog comparator. voltage reference enable signals and start-up time the voltage reference has a start-up time that may influence the way it should be used. the start-up time is given in table 18. to save power, the reference is not always turned on. the reference is on during the following situations: 1. when the bod is enabled (by pr ogramming the bodlevel [2..0] fuse). 2. when the bandgap reference is connected to the analog comparator (by setting the acbg bit in acsr). thus, when the bod is not enabled, after setting the acbg bit, the user must always allow the reference to start up before the output from the analog comparator is used. to reduce power consumption in power-down mode, the user can avoid the three condi- tions above to ensure that the reference is turned off before entering power-down mode. note: 1. values are guidelines only. actual values are tbd. table 18. internal voltage reference characteristics (1) symbol parameter condi tion min typ max units v bg bandgap reference voltage v cc = 2.7v, t a =25c 1.0 1.1 1.2 v t bg bandgap reference start-up time v cc = 2.7v, t a =25c 40 70 s i bg bandgap reference current consumption v cc = 2.7v, t a =25c 15 a
38 attiny2313/v 2543f?avr?08/04 watchdog timer attiny2313 has an enhanced watchdog timer (wdt). the main features are:  clocked from separate on-chip oscillator  3 operating modes ? interrupt ? system reset ? interrupt and system reset  selectable time-out pe riod from 16ms to 8s  possible hardware fuse watchdog al ways on (wdton) for fail-safe mode figure 20. watchdog timer the watchdog timer (wdt) is a timer counting cycles of a separate on-chip 128 khz oscillator. the wdt gives an interrupt or a system reset when the counter reaches a given time-out value. in normal operation mo de, it is required that the system uses the wdr - watchdog timer reset - instruction to restart the counter before the time-out value is reached. if the system doesn't restart the counter, an interrupt or system reset will be issued. in interrupt mode, the wdt gives an interrupt when the timer expires. this interrupt can be used to wake the device from sleep-modes, and also as a general system timer. one example is to limit the maximum time allow ed for certain operations, giving an interrupt when the operation has run longer than expected. in system reset mode, the wdt gives a reset when the timer expires. this is typically used to prevent system hang-up in case of runaway code. the third mode, interrupt and system reset mode, combines the other two modes by first giving an interrupt and then switch to system reset mode. this mode will for instance allow a safe shutdown by saving critical para meters before a sys- tem reset. the watchdog always on (wdton) fuse, if programmed, will force the watchdog timer to system reset mode. with the fuse programmed the system reset mode bit (wde) and interrupt mode bit (wdie) are locked to 1 and 0 respectively. to further ensure program security, alterations to the watchdog set-up must follow timed sequences. the sequence for clearing wde and changing time-out configuration is as follows: 1. in the same operation, write a logic one to the watchdog change enable bit (wdce) and wde. a logic one must be written to wde regardless of the previ- ous value of the wde bit. 2. within the next four clock cycles, write the wde and watchdog prescaler bits (wdp) as desired, but with the wdce bit cleared. this must be done in one operation. 128khz oscillator osc/2k osc/4k osc/8k osc/16k osc/32k osc/64k osc/128k osc/256k osc/512k osc/1024k wdp0 wdp1 wdp2 wdp3 watchdog reset wde wdif wdie mcu reset interrupt
39 attiny2313/v 2543f?avr?08/04 the following code example shows one assembly and one c function for turning off the watchdog timer. the example assumes that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts wi ll occur during the execution of these functions. note: 1. the example code assumes that the pa rt specific header file is included. note: if the watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition , the device will be reset and the watchdog timer will stay enabled. if the code is not set up to handle the watchdog, this might lead to an eternal loop of time-out resets. to avoid this situation, th e application software should always clear the assembly code example (1) wdt_off: ; turn off global interrupt cli ; reset watchdog timer wdr ; clear wdrf in mcusr in r16, mcusr andi r16, (0xff & (0< 40 attiny2313/v 2543f?avr?08/04 watchdog system reset flag (wdrf) and the wde control bit in the initialisation rou- tine, even if the watchdog is not in use. the following code example shows one assembly and one c function for changing the time-out value of the watchdog timer. note: 1. the example code assumes that the pa rt specific header file is included. note: the watchdog timer should be reset before any change of the wdp bits, since a change in the wdp bits can result in a time -out when switching to a shorter time-out period. assembly code example (1) wdt_prescaler_change: ; turn off global interrupt cli ; reset watchdog timer wdr ; start timed sequence in r16, wdtcsr ori r16, (1< 41 attiny2313/v 2543f?avr?08/04 watchdog timer control register - wdtcsr  bit 7 - wdif: watchdog interrupt flag this bit is set when a time-out occurs in the watchdog timer and the watchdog timer is configured for interrupt. wdif is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, wdif is cleared by writing a logic one to the flag. when the i-bit in sreg and wdie are set, the watchdog time-out interrupt is executed.  bit 6 - wdie: watchdog interrupt enable when this bit is written to one and the i-bit in the status register is set, the watchdog interrupt is enabled. if wde is cleared in combination with this setting, the watchdog timer is in interrupt mode, and the corresponding interrupt is executed if time-out in the watchdog timer occurs. if wde is set, the watchdog timer is in interrupt and system reset mode. the first time-out in the watchdog timer will set wdif. executing the corresponding interrupt vector will clear wdie and wdif automatically by hardware (the wa tchdog goes to sys- tem reset mode). this is useful for keeping the watchdog timer security while using the interrupt. to stay in interrupt and system reset mode, wdie must be set after each interrupt. this should however not be done within the interrupt service routine itself, as this might compromise the safety-function of the watchdog system reset mode. if the interrupt is not executed be fore the next time-out, a system reset will be applied.  bit 4 - wdce: watchdog change enable this bit is used in timed sequences for changing wde and prescaler bits. to clear the wde bit, and/or change the prescaler bits, wdce must be set. once written to one, ha rdware will clear wdce after four clock cycles.  bit 3 - wde: watchdog system reset enable wde is overridden by wdrf in mcusr. this means that wde is always set when wdrf is set. to clear wde, wdrf must be cl eared first. this feature ensures multiple resets during conditions causing failure, and a safe start-up after the failure.  bit 5, 2..0 - wdp3..0: watchdog timer prescaler 3, 2, 1 and 0 the wdp3..0 bits determine the watchdog timer prescaling when the watchdog timer is running. the different prescaling values and their corresponding time-out periods are shown in table 20 on page 42. bit 76543210 wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 wdtcsr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value0000x000 table 19. watchdog timer configuration wdton wde wdie mode action on time-out 0 0 0 stopped none 0 0 1 interrupt mode interrupt 0 1 0 system reset mode reset 011 interrupt and system reset mode interrupt, then go to system reset mode 1 x x system reset mode reset
42 attiny2313/v 2543f?avr?08/04 table 20. watchdog timer prescale select wdp3 wdp2 wdp1 wdp0 number of wdt oscillator cycles typical time-out at v cc = 5.0v 0 0 0 0 2k (2048) cycles 16 ms 0 0 0 1 4k (4096) cycles 32 ms 0 0 1 0 8k (8192) cycles 64 ms 0 0 1 1 16k (16384) cycles 0.125 s 0 1 0 0 32k (32768) cycles 0.25 s 0 1 0 1 64k (65536) cycles 0.5 s 0 1 1 0 128k (131072) cycles 1.0 s 0 1 1 1 256k (262144) cycles 2.0 s 1 0 0 0 512k (524288) cycles 4.0 s 1 0 0 1 1024k (1048576) cycles 8.0 s 1010 reserved 1011 1100 1101 1110 1111
43 attiny2313/v 2543f?avr?08/04 interrupts this section describes the specifics of the interrupt handling as performed in attiny2313. for a general explanation of the avr interrupt handling, refer to ?reset and interrupt handling? on page 11. interrupt vectors in attiny2313 table 21. reset and interrupt vectors vector no. program address source interrupt definition 1 0x0000 reset external pin, power-on reset, brown-out reset, and watchdog reset 2 0x0001 int0 external interrupt request 0 3 0x0002 int1 external interrupt request 1 4 0x0003 timer1 capt timer/counter1 capture event 5 0x0004 timer1 compa timer/counter1 compare match a 6 0x0005 timer1 ovf timer/counter1 overflow 7 0x0006 timer0 ovf timer/counter0 overflow 8 0x0007 usart0, rx usart0, rx complete 9 0x0008 usart0, udre usart0 data register empty 10 0x0009 usart0, tx usart0, tx complete 11 0x000a analog comp analog comparator 12 0x000b pcint pin change interrupt 13 0x000c timer1 compb timer/counter1 compare match b 14 0x000d timer0 compa timer/counter0 compare match a 15 0x000e timer0 compb timer/counter0 compare match b 16 0x000f usi start usi start condition 17 0x0010 usi overflow usi overflow 18 0x0011 ee ready eeprom ready 19 0x0012 wdt overflow watchdog timer overflow
44 attiny2313/v 2543f?avr?08/04 the most typical and general program setup for the reset and interrupt vector addresses in attiny2313 is: address labels code comments 0x0000 rjmp reset ; reset handler 0x0001 rjmp int0 ; external interrupt0 handler 0x0002 rjmp int1 ; external interrupt1 handler 0x0003 rjmp tim1_capt ; timer1 capture handler 0x0004 rjmp tim1_compa ; timer1 comparea handler 0x0005 rjmp tim1_ovf ; timer1 overflow handler 0x0006 rjmp tim0_ovf ; timer0 overflow handler 0x0007 rjmp usart0_rxc ; usart0 rx complete handler 0x0008 rjmp usart0_dre ; usart0,udr empty handler 0x0009 rjmp usart0_txc ; usart0 tx complete handler 0x000a rjmp ana_comp ; analog comparator handler 0x000b rjmp pcint ; pin change interrupt 0x000c rjmp timer1_compb ; timer1 compare b handler 0x000d rjmp timer0_compa ; timer0 compare a handler 0x000e rjmp timer0_compb ; timer0 compare b handler 0x000f rjmp usi_start ; usi start handler 0x0010 rjmp usi_overflow ; usi overflow handler 0x0011 rjmp ee_ready ; eeprom ready handler 0x0012 rjmp wdt_overflow ; watchdog overflow handler ; 0x0013 reset: ldi r16, low(ramend); main program start 0x0014 out spl,r16 set stack pointer to top of ram 0x0015 sei ; enable interrupts 0x0016 xxx ... ... ... ...
45 attiny2313/v 2543f?avr?08/04 i/o-ports introduction all avr ports have true read-modify-write functionality when used as general digital i/o ports. this means that the direction of one port pin can be changed without uninten- tionally changing the direction of any other pin with the sbi and cbi instructions. the same applies when changing drive value (if c onfigured as output) or enabling/disabling of pull-up resistors (if configured as input). each output buffer has symmetrical drive characteristics with both high sink and source capability. the pin dr iver is strong enough to drive led displays directly. all port pins have individually selectable pull-up resistors with a supply-voltage invariant resistance. all i/o pins have protection diodes to both v cc and ground as indicated in figure 21. refer to ?electrical characteristics? on page 176 for a complete list of parameters. figure 21. i/o pin equivalent schematic all registers and bit references in this section are written in general form. a lower case ?x? represents the numbering letter for the port, and a lower case ?n? represents the bit number. however, when using the register or bit defines in a program, the precise form must be used. for example, portb3 for bit no. 3 in port b, here documented generally as portxn. the physical i/o registers and bit locations are listed in ?register descrip- tion for i/o-ports? on page 57. three i/o memory address locations are allocated for each port, one each for the data register ? portx, data direction register ? ddrx, and the port input pins ? pinx. the port input pins i/o location is read only, while the data register and the data direction register are read/write. however, writing a logic one to a bit in t he pinx register, will result in a toggle in the corresponding bit in the data register. in addition, the pull-up disable ? pud bit in mcucr disables the pull- up function for all pins in all ports when set. using the i/o port as general dig ital i/o is described in ?ports as general digital i/o? on page 46. most port pins are multiplexed with alternate functions for the peripheral fea- tures on the device. how each alternate function interferes with the port pin is described in ?alternate port functions? on page 50. refer to the individual module sections for a full description of the alternate functions. c pin logic r pu see figure "general digital i/o" for details pxn
46 attiny2313/v 2543f?avr?08/04 note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital i/o. ports as general digital i/o the ports are bi-directional i/o ports with optional internal pull-ups. figure 22 shows a functional description of one i/o-port pin, here generically called pxn. figure 22. general digital i/o (1) note: 1. wrx, wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. configuring the pin each port pin consists of three register bits: ddxn, portxn, and pinxn. as shown in ?register description for i/o-ports? on page 57, the ddxn bits are accessed at the ddrx i/o address, the portxn bits at t he portx i/o address, and the pinxn bits at the pinx i/o address. the ddxn bit in the ddrx register selects the direction of this pin. if ddxn is written logic one, pxn is configured as an output pin. if ddxn is written logic zero, pxn is config- ured as an input pin. if portxn is written logic one when the pin is configured as an input pin, the pull-up resistor is activated. to switch the pull-up resistor off, portxn has to be written logic zero or the pin has to be configured as an output pin. the port pins are tri-stated when reset condition becomes active, even if no clocks are running. if portxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). if portxn is written logic zero when the pin is configured as an out- put pin, the port pin is driven low (zero). clk rpx rrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q reset reset q q d q q d clr portxn q q d clr ddxn pinxn data b u s sleep sleep: sleep control pxn i/o wpx 0 1 wrx wpx: write pinx register
47 attiny2313/v 2543f?avr?08/04 toggling the pin writing a logic one to pinxn toggles the value of portxn, independent on the value of ddrxn. note that the sbi instruction can be used to toggle one single bit in a port. switching between input and output when switching between tri-state ({ddxn, portxn} = 0b00) and output high ({ddxn, portxn} = 0b11), an intermed iate state with either pull-up enabled {ddx n, portxn} = 0b01) or output low ({ddxn, portxn} = 0b10) must occur. normally, the pull-up enabled state is fully acceptable, as a high -impedant environment will not notice the dif- ference between a strong high driver and a pull-up. if this is not the case, the pud bit in the mcucr register can be set to di sable all pull-ups in all ports. switching between input with pull-up and output low generates the same problem. the user must use either the tri-state ({ddxn, portxn} = 0b00) or the output high state ({ddxn, portxn} = 0b11) as an intermediate step. table 22 summarizes the control signals for the pin value. reading the pin value independent of the setting of data direction bit ddxn, the port pin can be read through the pinxn register bit. as shown in figure 22, the pinxn register bit and the preceding latch constitute a synchronizer. this is needed to avoid metastability if the physical pin changes value near the edge of the internal cl ock, but it also introduces a delay. figure 23 shows a timing diagram of the synchroni zation when reading an externally applied pin value. the maximum and minimum propagation delays are denoted t pd,max and t pd,min respectively. figure 23. synchronization when reading an externally applied pin value table 22. port pin configurations ddxn portxn pud (in mcucr2) i/o pull-up comment 0 0 x input no tri-state (hi-z) 0 1 0 input yes pxn will source current if ext. pulled low. 0 1 1 input no tri-state (hi-z) 1 0 x output no output low (sink) 1 1 x output no output high (source) xxx in r17, pinx 0x00 0xff instructions sync latch pinxn r17 xxx system clk t pd, max t pd, min
48 attiny2313/v 2543f?avr?08/04 consider the clock period starting shortly afte r the first falling edge of the system clock. the latch is closed when the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of t he ?sync latch? signal. the signal value is latched when the system clock goes low. it is clocked into the pinxn register at the suc- ceeding positive clock edge. as indicated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed between ? and 1? system clock period depending upon the time of assertion. when reading back a software assigned pin value, a nop instruction must be inserted as indicated in figure 24. the out instruction sets the ?sync latch? signal at the positive edge of the clock. in this case, the delay tpd through the synchronizer is 1 system clock period. figure 24. synchronization when reading a software assigned pin value out portx, r16 nop in r17, pinx 0xff 0x00 0xff system clk r16 instructions sync latch pinxn r17 t pd
49 attiny2313/v 2543f?avr?08/04 the following code example shows how to set port b pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. the resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. note: 1. for the assembly program, two tempor ary registers are used to minimize the time from pull-ups are set on pins 0, 1, 6, and 7, until the direction bits are correctly set, defining bit 2 and 3 as low and redefini ng bits 0 and 1 as strong high drivers. digital input enable and sleep modes as shown in figure 22, the digital input si gnal can be clamped to ground at the input of the schmitt trigger. the signal denoted sleep in the figure, is set by the mcu sleep controller in power-down mode, and standby mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to v cc /2. sleep is overridden for port pins enabled as external interrup t pins. if the external inter- rupt request is not enabled, sleep is active also for these pins. sleep is also overridden by various other alternate functions as described in ?alternate port func- tions? on page 50. if a logic high level (?one?) is present on an asynchronous external interrupt pin config- ured as ?interrupt on rising edge, falling edge, or any logic change on pin? while the external interrupt is not enabled, the corresponding exte rnal interrupt flag will be set when resuming from the above mentioned sle ep mode, as the clamping in these sleep mode produces the requested logic change. assembly code example (1) ... ; define pull-ups and set outputs high ; define directions for port pins ldi r16,(1< 50 attiny2313/v 2543f?avr?08/04 alternate port functions most port pins have alternate functions in addition to being general digital i/os. figure 25 shows how the port pin control signals fr om the simplified figure 22 can be overrid- den by alternate functions. the overriding signals may not be present in all port pins, but the figure serves as a generic description app licable to all port pins in the avr micro- controller family. figure 25. alternate port functions (1) note: 1. wrx, wpx, wdx, rrx, rpx, and rdx are common to all pins within the same port. clk i/o , sleep, and pud are common to all ports. all other signals are unique for each pin. table 23 summarizes the function of the overriding signals. the pin and port indexes from figure 25 are not shown in the succeed ing tables. the overriding signals are gen- erated internally in the modules having the alternate function. clk rpx rrx wrx rdx wdx pud synchronizer wdx: write ddrx wrx: write portx rrx: read portx register rpx: read portx pin pud: pullup disable clk i/o : i/o clock rdx: read ddrx d l q q set clr 0 1 0 1 0 1 dixn aioxn dieoexn pvovxn pvoexn ddovxn ddoexn puoexn puovxn puoexn: pxn pull-up override enable puovxn: pxn pull-up override value ddoexn: pxn data direction override enable ddovxn: pxn data direction override value pvoexn: pxn port value override enable pvovxn: pxn port value override value dixn: digital input pin n on portx aioxn: analog input/output pin n on portx reset reset q q d clr q q d clr q q d clr pinxn portxn ddxn data b u s 0 1 dieovxn sleep dieoexn: pxn digital input-enable override enable dieovxn: pxn digital input-enable override value sleep: sleep control pxn i/o 0 1 ptoexn wpx ptoexn: pxn, port toggle override enable wpx: write pinx
51 attiny2313/v 2543f?avr?08/04 the following subsections shortly describe the alternate functions for each port, and relate the overriding signals to the alternat e function. refer to the alternate function description for further details. table 23. generic description of overriding signals for alternate functions signal name full name description puoe pull-up override enable if this signal is set, the pull-up enable is controlled by the puov signal. if this signal is cleared, the pull-up is enabled when {ddxn, portxn, pud} = 0b010. puov pull-up override value if puoe is set, the pull-up is enabled/disabled when puov is set/cleared, regardless of the setting of the ddxn, portxn, and pud register bits. ddoe data direction override enable if this signal is set, the output driver enable is controlled by the ddov signal. if this signal is cleared, the output driver is enabled by the ddxn register bit. ddov data direction override value if ddoe is set, the output driver is enabled/disabled when ddov is set/cleared, regardless of the setting of the ddxn register bit. pvoe port value override enable if this signal is set and the output driver is enabled, the port value is controlled by the pvov signal. if pvoe is cleared, and the output driver is enabled, the port value is controlled by the portxn register bit. pvov port value override value if pvoe is set, the port value is set to pvov, regardless of the setting of the portxn register bit. ptoe port toggle override enable if ptoe is set, the portxn register bit is inverted. dieoe digital input enable override enable if this bit is set, the digital input enable is controlled by the dieov signal. if this signal is cleared, the digital input enable is determined by mcu state (normal mode, sleep mode). dieov digital input enable override value if dieoe is set, the digital input is enabled/disabled when dieov is set/cleared, regardless of the mcu state (normal mode, sleep mode). di digital input this is the digital input to alternate functions. in the figure, the signal is connected to the output of the schmitt trigger but before the synchronizer. unless the digital input is used as a clock source, the module with the alternate function will use its own synchronizer. aio analog input/output this is the analog input/output to/from alternate functions. the signal is connected directly to the pad, and can be used bi-directionally.
52 attiny2313/v 2543f?avr?08/04 mcu control register ? mcucr  bit 7 ? pud: pull-up disable when this bit is written to one, the pull-ups in the i/o ports are disabled even if the ddxn and portxn registers are configured to enable the pull-ups ({ddxn, portxn} = 0b01). see ?configuring the pin? on page 46 for more details about this feature. alternate functions of port a the port a pins with alternate functions are as shown in table 5. alternate functions of port b the port b pins with alternate functions are shown in table 25. the alternate pin configuration is as follows:  usck/scl/pcint7 - port b, bit 7 usck: three-wire mode univer sal serial interface clock. scl: two-wire mode serial clock for usi two-wire mode. pcint7: pin change interrupt source 7. the pb7 pin can serve as an external interrupt source.  do/pcint6 - port b, bit 6 do: three-wire mode universal serial interface data output. three-wire mode data out- put overrides portb6 value and it is driven to the port when data direction bit ddb6 is set (one). however the portb6 bit still controls the pull-up enabling pull-up, if direction is input and portb6 is set (one). pcint6: pin change interrupt source 6. the pb6 pin can serve as an external interrupt source.  di/sda/pcint5 - port b, bit 5 bit 7 6 5 4 3 2 1 0 pud sm1 se sm0 isc11 isc10 isc01 isc00 mcucr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 24. port a pins alternate functions port pin alternate function pa2 reset, dw pa 1 x ta l 2 pa0 xtal1 table 25. port b pins alternate functions port pin alternate functions pb7 usck/scl/pcint7 pb6 do/pcint6 pb5 di/sda/pcint5 pb4 oc1b/pcint4 pb3 oc1a/pcint3 pb2 oc0a/pcint2 pb1 ain1/pcint1 pb0 ain0/pcint0
53 attiny2313/v 2543f?avr?08/04 di: three-wire mode universal serial interface data input. three-wire mode does not override normal port functions, so pin must be configured as an input. sda: two-wire mode serial interface data. pcint5: pin change interrupt source 5. the pb5 pin can serve as an external interrupt source.  oc1b/pcint4 ? port b, bit 4 oc1b: output compare match b output: the pb4 pin can serve as an external output for the timer/counter1 output compare b. the pin has to be configured as an output (ddb6 set (one)) to serve this function. the oc1b pin is also the output pin for the pwm mode timer function. pcint4: pin change interrupt source 4. the pb4 pin can serve as an external interrupt source.  oc1a/pcint3 ? port b, bit 3 oc1a: output compare match a output: the pb3 pin can serve as an external output for the timer/counter1 output compare a. the pin has to be configured as an output (ddb3 set (one)) to serve this function. the oc1a pin is also the output pin for the pwm mode timer function. pcint3: pin change interrupt source 3: the pb3 pin can serve as an external interrupt source.  oc0a/pcint2 ? port b, bit 2 oc0a: output compare match a output. the pb2 pin can serve as an external output for the timer/counter0 output compare a. the pin has to be configured as an output (ddb2 set (one)) to serve this function. the oc0a pin is also the output pin for the pwm mode timer function. pcint2: pin change interrupt source 2. the pb2 pin can serve as an external interrupt source.  ain1/pcint1 ? port b, bit 1 ain1: analog comparator negative input . configure the port pin as input with the inter- nal pull-up switched off to avoid the digital port function from interfering with the function of the analog comparator. pcint1: pin change interrupt source 1. the pb1 pin can serve as an external interrupt source.  ain0/pcint0 ? port b, bit 0 ain0: analog comparator positive input. configure the port pin as input with the internal pull-up switched off to avoid the digital port function from interfering with the function of the analog comparator. pcint0: pin change interrupt source 0. the pb0 pin can serve as an external interrupt source. table 26 and table 27 relate the alternate functions of port b to the overriding signals shown in figure 25 on page 50. spi mstr input and spi slave output constitute the miso signal, while mosi is divide d into spi mstr output and spi slave input.
54 attiny2313/v 2543f?avr?08/04 table 26. overriding signals for alternate functions in pb7..pb4 signal name pb7/usck/ scl/pcint7 pb6/do/pcint6 pb5/sda/ di/pcint5 pb4/oc1b/ pcint4 puoe 0 0 0 0 puov 0 0 0 0 ddoe usi_two_wire 0 usi_two_wire 0 ddov (usi_scl_hold + portb7 )ddb7 0(sda + portb5 ) ddrb5 0 pvoe usi_two_wire  ddrb7 usi_three_wire usi_two_wire  ddrb5 oc1b_pvoe pvov 0 do 0 0oc1b_pvov ptoe usi_ptoe 0 0 0 dieoe (pcint7pcie) +usisie (pcint6pcie) (pcint5pcie) + usisie (pcint4pcie) dieov 1 1 1 1 di pcint7 input usck input scl input pcint6 input pcint5 input sda input di input pcint4 input aio ? ? ? ? table 27. overriding signals for alternate functions in pb3..pb0 signal name pb3/oc1a/ pcint3 pb2/oc0a/ pcint2 pb1/ain1/ pcint1 pb0/ain0/ pcint0 puoe 0 0 0 0 puov 0 0 0 0 ddoe 0 0 0 0 ddov 0 0 0 0 pvoe oc1a_pvoe oc0a_pvoe 0 0 pvov oc1a_pvov oc0a_pvov 0 0 ptoe 0 0 0 0 dieoe (pcint3  pcie) (pcint2  pcie ) (pcint1  pcie) (pcint0  pcie) dieov 1 1 1 1 di pcint7 input pcint6 input pcint5 input pcint4 input aio ? ? ain1 ain0
55 attiny2313/v 2543f?avr?08/04 alternate functions of port d the port d pins with alternate functions are shown in table 28. the alternate pin configuration is as follows:  icp ? port d, bit 6 icp: timer/counter1 input capture pin. the pd6 pin can act as an input capture pin for timer/counter1  oc1b/t1 ? port d, bit 5 oc0b: output compare match b output: the pd5 pin can serve as an external output for the timer/counter0 output compare b. the pin has to be configured as an output (ddb5 set (one)) to serve this function. the oc0b pin is also the output pin for the pwm mode timer function. t1: timer/counter1 external counter clock input is enabled by setting (one) the bits cs02 and cs01 in the timer/counter1 control register (tccr1).  t0 ? port d, bit 4 t0: timer/counter0 external counter clock input is enabled by setting (one) the bits cs02 and cs01 in the timer/counter0 control register (tccr0).  int1 ? port d, bit 3 int0: external interrupt source 0. the pd3 pin can serve as an external interrupt source to the mcu.  int0/xck/ckout ? port d, bit 2 int1: external interrupt source 1. the pd2 pin can serve as en external interrupt source to the mcu. xck: usart transfer clock used on ly by synchronous transfer mode. ckout: system clock output txd ? port d, bit 1 txd: uart data transmitter.  rxd ? port d, bit 0 rxd: uart data receiver. table 28. port d pins alternate functions port pin alternate function pd6 icp pd5 oc0b/t1 pd4 t0 pd3 int1 pd2 int0/xck/ckout pd1 txd pd0 rxd
56 attiny2313/v 2543f?avr?08/04 table 29 and table 30 relates the alternate fu nctions of port d to the overriding signals shown in figure 25 on page 50. table 29. overriding signals for alternate functions pd7..pd4 signal name pd6/icp pd5/oc1b/t1 pd4/t0 puoe000 puov000 ddoe 0 0 0 ddov 0 0 0 pvoe 0 oc1b_pvoe 0 pvov 0 oc1b_pvov 0 ptoe000 dieoe icp enable t1 enable t0 enable dieov111 di icp input t1 input t0 input aio??ain1 table 30. overriding signals for alternate functions in pd3..pd0 signal name pd3/int1 pd2/int0/xck/ ckout pd1/txd pd0/rxd puoe 0 0 txd_oe rxd_oe puov 0 0 0 portd0  pud ddoe 0 0 txd_oe rxd_en ddov 0 0 1 0 pvoe 0 xcko_pvoe txd_oe 0 pvov 0 xcko_pvov txd_pvov 0 ptoe 0 0 0 0 dieoe int1 enable int0 enable/ xck input enable 00 dieov 1 1 0 0 di int1 input int0 input/ xck input ? rxd input aio ? ? ? ?
57 attiny2313/v 2543f?avr?08/04 register description for i/o-ports port a data register ? porta port a data direction register ? ddra port a input pins address ? pina port b data register ? portb port b data direction register ? ddrb port b input pins address ? pinb port d data register ? portd port d data direction register ? ddrd port d input pins address ? pind bit 76543210 ?????porta2porta1porta0 porta read/writerrrrrr/wr/wr/w initial value00000000 bit 76543210 ????? dda2 dda1 dda0 ddra read/writerrrrrr/wr/wr/w initial value00000000 bit 76543210 ????? pina2 pina1 pina0 pina read/writerrrrrr/wr/wr/w initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 portb7 portb6 portb5 portb4 portb3 portb2 portb1 portb0 portb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ddb7 ddb6 ddb5 ddb4 ddb3 ddb2 ddb1 ddb0 ddrb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 pinb7 pinb6 pinb5 pinb4 pi nb3 pinb2 pinb1 pinb0 pinb read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value n/a n/a n/a n/a n/a n/a n/a n/a bit 76543210 ? portd6 portd5 portd4 portd3 portd2 portd1 portd0 portd read/write r r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ? ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 ddrd read/write r r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ? pind6 pind5 pind4 pind3 pind2 pind1 pind0 pind read/write r r/w r/w r/w r/w r/w r/w r/w initial value n/a n/a n/a n/a n/a n/a n/a n/a
58 attiny2313/v 2543f?avr?08/04 external interrupts the external interrupts are triggered by the int0 pin, int1 pin or any of the pcint7..0 pins. observe that, if enabled, the interrupts will trigger even if the int0, int1or pcint7..0 pins are configured as outputs. this feature provides a way of generating a software interr upt. the pin change inte rrupt pci1 will trigger if any enabled pcint7..8 pin toggles. pin change interr upts pci0 will trigger if any enabled pcint7..0 pin toggles. the pcmsk1 and pcmsk0 registers control which pins contribute to the pin change interrupts. pin change interrupts on pcint7..0 are detected asynchronously. this implies that these interrupts can be used for waking the part also from sleep modes other than idle mode. the int0 and int1 inte rrupts can be triggered by a fallin g or rising edge or a low level. this is set up as indicated in the specification for the external interrupt control register a ? eicra. when the int0 or int1 interrupt is enabled and is configured as level trig- gered, the interrupt will trigger as long as the pin is he ld low. note that recognition of falling or rising edge interrupt s on int0 and int1 requires th e presence of an i/o clock, described in ?clock systems and their distri bution? on page 21. low level interrupt on int0 and int1 is detected asynchronously. this implies that this interrupt can be used for waking the part from sleep modes other than idle mode. the i/o clock is halted in all sleep modes except idle mode. note that if a level triggered interrupt is used for wake-up from power-down, the required level must be held long enough for the mcu to co mplete the wake-up to trigger the level interrupt. if the level disappears before the end of the start-up time, the mcu will still wake up, but no interrupt will be generated. the start-up time is defined by the sut and cksel fuses as descr ibed in ?system clock and clock options? on page 21. mcu control register ? mcucr the external interrupt control register a contains control bits for interrupt sense control.  bit 3, 2 ? isc11, isc10: interrupt sense control 1 bit 1 and bit 0 the external interrupt 1 is activated by the external pin int1 if the sreg i-flag and the corresponding interrupt mask are set. the level and edges on the external int1 pin that activate the interrupt are defined in tabl e 32. the value on the int1 pin is sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. shorter pulses are not guaranteed to generate an interrupt. if low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt.  bit 1, 0 ? isc01, isc00: interrupt sense control 0 bit 1 and bit 0 the external interrupt 0 is activated by the external pin int0 if the sreg i-flag and the corresponding interrupt mask are set. the level and edges on the external int0 pin that bit 76543210 pud sm1 se smd isc11 isc10 isc01 isc00 mcucr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 table 31. interrupt 0 sense control isc11 isc10 description 0 0 the low level of int1 generates an interrupt request. 0 1 any logical change on int1 generates an interrupt request. 1 0 the falling edge of int1 generates an interrupt request. 1 1 the rising edge of int1 generates an interrupt request.
59 attiny2313/v 2543f?avr?08/04 activate the interrupt are defined in tabl e 32. the value on the int0 pin is sampled before detecting edges. if edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. shorter pulses are not guaranteed to generate an interrupt. if low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. general interrupt mask register ? gimsk  bit 7 ? int1: external interrupt request 1 enable when the int1 bit is set (one) and the i-bit in the status register (sreg) is set (one), the external pin interrupt is enabled. the interrupt sense control1 bits 1/0 (isc11 and isc10) in the mcu control register ? mcu cr ? define whether the external interrupt is activated on rising and/or falling edge of the int1 pin or leve l sensed. activity on the pin will cause an interrupt request even if int1 is configured as an output. the correspond- ing interrupt of external interrupt request 1 is executed from the int1 interrupt vector.  bit 6 ? int0: external interrupt request 0 enable when the int0 bit is set (one) and the i-bit in the status register (sreg) is set (one), the external pin interrupt is enabled. the interrupt sense control0 bits 1/0 (isc01 and isc00) in the mcu control register ? mcu cr ? define whether the external interrupt is activated on rising and/or falling edge of the int0 pin or leve l sensed. activity on the pin will cause an interrupt request even if int0 is configured as an output. the correspond- ing interrupt of external interrupt request 0 is executed from the int0 interrupt vector.  bit 5 ? pcie: pin change interrupt enable when the pcie bit is set (one) and the i-bit in the status register (sreg) is set (one), pin change interrupt 1 is enabled. any ch ange on any enabled pcint7..0 pin will cause an interrupt. the corresponding interrupt of pin change interrupt request is executed from the pci interrupt vector. pcint7..0 pins are enabled individually by the pcmsk register. table 32. interrupt 0 sense control isc01 isc00 description 0 0 the low level of int0 generates an interrupt request. 0 1 any logical change on int0 generates an interrupt request. 1 0 the falling edge of int0 generates an interrupt request. 1 1 the rising edge of int0 generates an interrupt request. bit 76543210 int1 int0 pcie ? ? ? ? ?gimsk read/write r/w r/w r/w r r r r r initial value 0 0 0 0 0 0 0 0
60 attiny2313/v 2543f?avr?08/04 external interrupt flag register ? eifr  bit 7 ? intf1: external interrupt flag 1 when an edge or logic change on the int1 pin triggers an interrupt request, intf1 becomes set (one). if the i-bit in sreg and the int1 bit in gimsk are set (one), the mcu will jump to the correspondi ng interrupt vector. the flag is cleared when the inter- rupt routine is executed. alternatively, the fl ag can be cleared by writing a logical one to it. this flag is always cl eared when int1 is configured as a level interrupt.  bit 6 ? intf0: external interrupt flag 0 when an edge or logic change on the int0 pin triggers an interrupt request, intf0 becomes set (one). if the i-bit in sreg and the int0 bit in gimsk are set (one), the mcu will jump to the correspondi ng interrupt vector. the flag is cleared when the inter- rupt routine is executed. alternatively, the fl ag can be cleared by writing a logical one to it. this flag is always cl eared when int0 is configured as a level interrupt.  bit 5 ? pcif: pin change interrupt flag when a logic change on any pcint7..0 pin triggers an interrupt request, pcif becomes set (one). if the i-bit in sreg and the pcie bit in gimsk are set (one), the mcu will jump to the corresponding interrupt vector. the flag is cleared when the interrupt routine is executed. alternatively, the flag can be cleared by writing a logical one to it. pin change mask register ? pcmsk  bit 7..0 ? pcint7..0: pin change enable mask 15..8 each pcint7..0-bit selects whether pin change interrupt is enabled on the correspond- ing i/o pin. if pcint7..0 is set and the pcie bit in gimsk is set, pin change interrupt is enabled on the corresponding i/o pin. if pcint7..0 is cleared, pin change interrupt on the corresponding i/o pin is disabled. bit 76543210 intf1 intf0 pcif ? ? ? ? ?eifr read/write r/w r/w r/w r r r r r initial value 0 0 0 0 0 0 0 0 bit 76543210 pcint7 pcint6 pcint5 pcint4 pcint3 pcint2 pcint1 pcint0 pcmsk read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
61 attiny2313/v 2543f?avr?08/04 8-bit timer/counter0 with pwm timer/counter0 is a general purpose 8-bi t timer/counter module, with two independent output compare units, and with pwm support. it allows accurate program execution timing (event management) and wave generation. the main features are:  two independent output compare units  double buffered out put compare registers  clear timer on compar e match (auto reload)  glitch free, phase correct pulse width modulator (pwm)  variable pwm period  frequency generator  three independent interrupt sources (tov0, ocf0a, and ocf0b) overview a simplified block diagram of the 8-bit time r/counter is shown in figure 26. for the actual placement of i/o pins, refer to ?pin out attiny2313? on page 2. cpu accessible i/o registers, including i/o bits and i/o pins , are shown in bold. the device-specific i/o register and bit locations are listed in the ?8-bit timer/counter register description? on page 72. figure 26. 8-bit timer/counter block diagram registers the timer/counter (tcnt0) and output compare registers (ocr0a and ocr0b) are 8-bit registers. interrupt request (abbreviated to int.req. in the figure) signals are all vis- ible in the timer interrupt flag register (tifr). all interrupts are individually masked with the timer interrupt mask register (tim sk). tifr and timsk are not shown in the figure. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the t0 pin. the clock select logic block controls which clock source and edge the timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no cloc k source is selected. the output from the clock select logic is referred to as the timer clock (clk t0 ). the double buffered output compare registers (ocr0a and ocr0b) is compared with the timer/counter value at all times. the result of the compare can be used by the waveform generator to generate a pwm or variable frequency output on the output clock select timer/counter data bus ocrna ocrnb = = tcntn waveform generation waveform generation ocna ocnb = fixed top value control logic = 0 top bottom count clear direction tovn (int.req.) ocna (int.req.) ocnb (int.req.) tccrna tccrnb tn edge detector ( from prescaler ) clk tn
62 attiny2313/v 2543f?avr?08/04 compare pins (oc0a and oc0b). see ?output compare unit? on page 63. for details. the compare match event will also set the compare flag (ocf0a or ocf0b) which can be used to generate an output compare interrupt request. definitions many register and bit references in this section are written in general form. a lower case ?n? replaces the timer/counter number, in this case 0. a lower case ?x? replaces the output compare unit, in this case compare unit a or co mpare unit b. however, when using the register or bit defines in a pr ogram, the precise form must be used, i.e., tcnt0 for accessing timer/counter0 counter value and so on. the definitions in table 33 are also used extensively throughout the document. timer/counter clock sources the timer/counter can be clocked by an intern al or an external clock source. the clock source is selected by the clock select lo gic which is controlled by the clock select (cs02:0) bits located in the timer/counte r control register (tccr0b). for details on clock sources and pre scaler, see ?timer/counter0 and timer/counter1 prescalers? on page 79. counter unit the main part of the 8-bit timer/counter is the programmable bi-directional counter unit. figure 27 shows a block diagram of the counter and its surroundings. figure 27. counter unit block diagram signal description (internal signals): count increment or decrement tcnt0 by 1. direction select between increment and decrement. clear clear tcnt0 (set all bits to zero). clk t n timer/counter clock, referred to as clk t0 in the following. top signalize that tcnt0 has reached maximum value. bottom signalize that tcnt0 has reached minimum value (zero). table 33. definitions bottom the counter reaches the bottom when it becomes 0x00. max the counter reaches its maximum when it becomes 0xff (decimal 255). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be the fixed value 0xff (max) or the value stored in the ocr0a register. the assignment is dependent on the mode of operation. data bus tcntn control logic count tovn (int.req.) clock select top tn edge detector ( from prescaler ) clk tn bottom direction clear
63 attiny2313/v 2543f?avr?08/04 depending of the mode of operation used, the counter is cleared, incremented, or dec- remented at each timer clock (clk t0 ). clk t0 can be generated from an external or internal clock source, selected by the clock select bits (cs02:0). when no clock source is selected (cs02:0 = 0) the timer is stopped. however, the tcnt0 value can be accessed by the cpu, regardless of whether clk t0 is present or not. a cpu write overrides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the wgm01 and wgm00 bits located in the timer/counter control register (tccr0a) and the wgm02 bit located in the timer/counter control register b (tccr0b). there are close connections between how the counter behaves (counts) and how waveforms are generated on the output compare output oc0a. for more details about advanced counting sequences and waveform generation, see ?modes of operation? on page 93. the timer/counter overflow flag (tov0) is set according to the mode of operation selected by the wgm01:0 bits. tov0 can be used for generating a cpu interrupt. output compare unit the 8-bit comparator continuously compares tcnt0 with the output compare regis- ters (ocr0a and ocr0b). whenever tcnt0 equals ocr0a or ocr0b, the comparator signals a match. a match will set the output compare flag (ocf0a or ocf0b) at the next timer clock cycle. if the corresponding interrupt is enabled, the out- put compare flag generates an output compare interrupt. the output compare flag is automatically cleared when the interrupt is executed. alternatively, the flag can be cleared by software by writing a logical one to its i/o bit location. the waveform gener- ator uses the match signal to generate an output according to operating mode set by the wgm02:0 bits and compare output mode (com0x1:0) bits. the max and bottom sig- nals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation (see ?modes of operation? on page 93). figure 28 shows a block diagram of the output compare unit. figure 28. output compare unit, block diagram ocfn x (int.req.) = (8-bit comparator ) ocrnx ocnx data bus tcntn wgmn1:0 waveform generator top focn comnx1:0 bottom
64 attiny2313/v 2543f?avr?08/04 the ocr0x registers are double buffered when using any of the pulse width modula- tion (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocr0x compare registers to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr0x register access may seem comple x, but this is not case. when the double buffering is enabled, the cpu has access to the ocr0x buffer register, and if double buffering is disabled the cp u will access the ocr0x directly. force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (foc0x) bit. forcing compare match will not set the ocf0x flag or reload /clear the timer, but the oc0x pin will be updated as if a real compare match had occurred (the com0x1:0 bits settings define whether the oc0x pin is set, cleared or toggled). compare match blocking by tcnt0 write all cpu write operations to the tcnt0 register will block any compare match that occur in the next timer clock cycle, even w hen the timer is stopped. this feature allows ocr0x to be initialized to the same value as tcnt0 without triggering an interrupt when the timer/counter clock is enabled. using the output compare unit since writing tcnt0 in any mode of operation will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt0 when using the output compare unit, independently of whether the timer/counter is running or not. if the value written to tcnt0 equals the ocr0x value, the compare match will be missed, resulting in incorrect waveform generation . similarly, do not write the tcnt0 value equal to bottom when the counter is down-counting. the setup of the oc0x should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc0x value is to use the force output compare (foc0x) strobe bits in normal mode. the oc0x registers keep their values even when changing between waveform generation modes. be aware that the com0x1:0 bits are not double buffered together with the compare value. changing the com0x1:0 bi ts will take effect immediately. compare match output unit the compare output mode (com0x1:0) bits have two functions. the waveform gener- ator uses the com0x1:0 bits for defining the output compare (oc0x) state at the next compare match. also, the com0x1:0 bits control the oc0x pin output source. figure 29 shows a simplified schematic of the logic affected by the com0x1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figur e are shown in bold. only the parts of the general i/o port cont rol registers (ddr and port) that are affected by the com0x1:0 bits are shown. when referring to the oc0x state, the reference is for the internal oc0x register, not the oc0x pin. if a system reset occur, the oc0x register is reset to ?0?.
65 attiny2313/v 2543f?avr?08/04 figure 29. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc0x) from the waveform generator if either of the com0x1:0 bits are set. however, the oc0x pin direction (input or output) is still controlled by the data dir ection register (ddr) for the port pin. the data direction register bit for the oc0x pin (ddr_oc0x) must be set as output before the oc0x value is visible on the pin. the port override function is indepen- dent of the waveform generation mode. the design of the output compare pin logic allows initialization of the oc0x state before the output is enabled. note that some com0x1:0 bit settings are reserved for certain modes of operation. see ?8-bit timer/counter register description? on page 72. compare output mode and waveform generation the waveform generator uses the com0x1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com0x1:0 = 0 tells the waveform generator that no action on the oc0x register is to be performed on the next compare match. for com- pare output actions in the non-pwm modes refer to figure 28 on page 63. for fast pwm mode, refer to table 26 on page 54, and for phase correct pwm refer to table 27 on page 54. a change of the com0x1:0 bits state will have effect at the first compare match after the bits are written. for non-pwm modes, the action can be forced to have immediate effect by using the foc0x strobe bits. modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm02:0) and compare output mode (com0x1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com0x1:0 bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com0x1:0 bits control whether the out- put should be set, cleared, or toggled at a compare match (see ?compare match output unit? on page 64.). for detailed timing information refer to figure 33, figure 34, figure 35 and figure 36 in ?timer/counter timing diagrams? on page 70. port ddr dq dq ocn pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focn clk i/o
66 attiny2313/v 2543f?avr?08/04 normal mode the simplest mode of operation is the normal mode (wgm02:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 8-bit value (top = 0xff) and then restarts from the bottom (0x00). in normal operation the timer/counter overflow flag (tov0) will be set in the same timer cloc k cycle as the tcnt0 becomes zero. the tov0 flag in this case behaves like a ninth bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov0 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the output compare unit can be used to generate interrupts at some given time. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm02:0 = 2), the ocr0a register is used to manipulate the counter resolution. in ctc mode the counter is cleared to zero when the counter value (tcnt0) matches the ocr0 a. the ocr0a defines the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies th e operation of counting external events. the timing diagram for the ctc mode is shown in figure 30. the counter value (tcnt0) increases until a compare match occurs between tcnt0 and ocr0a, and then counter (tcnt0) is cleared. figure 30. ctc mode, timing diagram an interrupt can be generated each time the counter value reaches the top value by using the ocf0a flag. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing top to a value close to bottom when the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr0a is lower than the current value of tcnt0, the counter will miss the compare match. the counter will then have to count to its maxi mum value (0xff) and wrap around starting at 0x00 before the compare match can occur. for generating a waveform output in ctc mode, the oc0a output can be set to toggle its logical level on each compare match by setting the compare output mode bits to toggle mode (com 0a1:0 = 1). the oc0a value will not be visible on the port pin unless the data direction for the pin is set to output. the waveform generated will have a maxi- tcntn ocn (toggle) ocnx interrupt flag set 1 4 period 2 3 (comnx1:0 = 1)
67 attiny2313/v 2543f?avr?08/04 mum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero (0x00). the waveform frequency is defined by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tov0 flag is set in the same timer clock cycle that the counter counts from max to 0x00. fast pwm mode the fast pulse width modulation or fast pwm mode (wgm02:0 = 3 or 7) provides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm option by its single-slope operation. the counter counts from bottom to top then restarts from bottom. top is defined as 0xff when wgm2:0 = 3, and ocr0a when wgm2:0 = 7. in non-inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tcnt0 and ocr0x, and set at bottom. in inverting compare output mode, the output is set on compare match and cleared at bottom. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase co rrect pwm mode that use dual-slope opera- tion. this high frequency makes the fast pwm mode well suited for power regulation, rectification, and dac applications. high fr equency allows physicall y small sized exter- nal components (coils, capacitors), and therefore reduces total system cost. in fast pwm mode, the counter is incremented until the counter value matches the top value. the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 29. the tcnt0 value is in the timing diagram shown as a histogram for illustrating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes represent compare matches between ocr0x and tcnt0. figure 31. fast pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches top. if the interrupt is enabled, the interrupt handler routine can be used for updating the com- pare value. in fast pwm mode, the compare unit allows generation of pwm waveforms on the oc0x pins. setting the com0x1:0 bits to two will produce a non-inverted pwm and an f ocnx f clk_i/o 2 n 1 ocrnx + () ?? ------------------------------------------------- - = tcntn ocrnx update and tovn interrupt flag set 1 period 2 3 ocn ocn (comnx1:0 = 2) (comnx1:0 = 3) ocrnx interrupt flag set 4 5 6 7
68 attiny2313/v 2543f?avr?08/04 inverted pwm output can be generated by setting the com0x1:0 to three: setting the com0a1:0 bits to one allows the ac0a pin to toggle on compare matches if the wgm02 bit is set. this option is not avai lable for the oc0b pin (see table 26 on page 54). the actual oc 0x value will only be visible on the por t pin if the data direction for the port pin is set as output. the pwm waveform is generated by setting (or clearing) the oc0x register at the compare match between ocr0x and tcnt0, and clearing (or setting) the oc0x register at the timer clo ck cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr0a is set equal to bottom, the output will be a narro w spike for each max+1 timer cl ock cycle. setting the ocr0a equal to max will result in a constantly high or low output (depending on t he polarity of the output set by the com0a1:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by setting oc0x to toggle its logical leve l on each compare match (com0x1:0 = 1). the waveform generated will have a maximum frequency of f oc0 = f clk_i/o /2 when ocr0a is set to zero. this feature is similar to t he oc0a toggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast pwm mode. phase correct pwm mode the phase correct pwm mode (wgm02:0 = 1 or 5) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is based on a dual-slope operation. the counter counts repeatedly from bottom to top and then from top to bottom. top is defined as 0xff when wgm2:0 = 1, and ocr0a when wgm2:0 = 5. in non-inverting compare output mode, the output compare (oc0x) is cleared on the compare match between tcnt0 and ocr0x while upcounting, and set on the compare match while down-counting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmetric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. in phase correct pwm mode the counter is incremented until the counter value matches top. when the counter reaches top, it changes the count direction. the tcnt0 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 32. the tcnt0 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagra m includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt0 slopes repre- sent compare matches between ocr0x and tcnt0. f ocnxpwm f clk_i/o n 256 ? ------------------ =
69 attiny2313/v 2543f?avr?08/04 figure 32. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov0) is set each time the counter reaches bot- tom. the interrupt flag can be used to generate an interrupt each time the counter reaches the bottom value. in phase correct pwm mode, the compare unit allows generation of pwm waveforms on the oc0x pins. setting the com0x1:0 bits to two will produce a non-inverted pwm. an inverted pwm output can be generated by setting the com0x1:0 to three: setting the com0a0 bits to one allows the oc0a pin to toggle on compare matches if the wgm02 bit is set. this option is not available for the oc0b pin (see table 27 on page 54). the actual oc0x value will only be visible on the port pin if the data direction for the port pin is set as output. the pwm waveform is generated by clearing (or setting) the oc0x register at the compare match between ocr0x and tcnt0 when the counter incre- ments, and setting (or clearing) the oc0x register at compare match between ocr0x and tcnt0 when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the following equation: the n variable represents the prescale factor (1, 8, 64, 256, or 1024). the extreme values for the ocr0a register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr0a is set equal to bottom, the output will be cont inuously low and if set e qual to max the output will be continuously high for non-inverted pwm mode. for inverted pw m the output will have the opposite logic values. at the very start of period 2 in figure 32 ocn has a transition from high to low even though there is no compare match. the point of this transition is to guarantee symmetry around bottom. there are two cases that give a transition without compare match.  ocr0a changes its value from max, like in figure 32. when the ocr0a value is max the ocn pin value is the same as the result of a down-counting compare tovn interrupt flag set ocnx interrupt flag set 1 2 3 tcntn period ocn ocn (comnx1:0 = 2) (comnx1:0 = 3) ocrnx update f ocnxpcpwm f clk_i/o n 510 ? ------------------ =
70 attiny2313/v 2543f?avr?08/04 match. to ensure symmetry around bottom the ocn value at max must correspond to the result of an up-counting compare match.  the timer starts counting from a value higher than the one in ocr0a, and for that reason misses the compare match and hence the ocn change that would have happened on the way up. timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t0 ) is therefore shown as a clock enable signal in the followi ng figures. the figures include information on when interrupt flags are set. figure 33 contains timing data for basic timer/counter operation. the figure shows the count sequence close to the max value in all modes other than phase correct pwm mode. figure 33. timer/counter timing diagram, no prescaling figure 33 shows the same timing data, but with the prescaler enabled. figure 34. timer/counter timing diagram, with prescaler (f clk_i/o /8) figure 35 shows the setting of ocf0b in all modes and ocf0a in all modes except ctc mode and pwm mode, where ocr0a is top. figure 35. timer/counter timing diagram, setting of ocf0x, with prescaler (f clk_i/o /8) clk tn (clk i/o /1) tovn clk i/o tcntn max - 1 max bottom bottom + 1 tovn tcntn max - 1 max bottom bottom + 1 clk i/o clk tn (clk i/o /8) ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o /8)
71 attiny2313/v 2543f?avr?08/04 figure 36 shows the setting of ocf0a and the clearing of tcnt0 in ctc mode and fast pwm mode where ocr0a is top. figure 36. timer/counter timing diagram, clear timer on compare match mode, with prescaler (f clk_i/o /8) ocfnx ocrnx tcntn (ctc) top top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8)
72 attiny2313/v 2543f?avr?08/04 8-bit timer/counter register description timer/counter control register a ? tccr0a  bits 7:6 ? com0a1:0: compare match output a mode these bits control the output compare pin (oc0a) behavior. if one or both of the com0a1:0 bits are set, the oc0a output overrides the normal port functionality of the i/o pin it is connected to. ho wever, note that t he data direction register (ddr) bit cor- responding to the oc0a pin must be set in order to enable the output driver. when oc0a is connected to the pin, the func tion of the com0a1:0 bits depends on the wgm02:0 bit setting. table 34 shows the com0a1:0 bit functionality when the wgm02:0 bits are set to a normal or ctc mode (non-pwm). table 35 shows the com0a1:0 bit functionality when the wgm01:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0a equ als top and com0a1 is set. in this case, the compare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 67 for more details. bit 7 6 5 4 3 2 1 0 com0a1 com0a0 com0b1 com0b0 ? ? wgm01 wgm00 tccr0a read/write r/w r/w r/w r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 table 34. compare output mode, non-pwm mode com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 0 1 toggle oc0a on compare match 1 0 clear oc0a on compare match 1 1 set oc0a on compare match table 35. compare output mode, fast pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 0 1 wgm02 = 0: normal port operation, oc0a disconnected. wgm02 = 1: toggle oc0a on compare match. 1 0 clear oc0a on compare match, set oc0a at top 1 1 set oc0a on compare match, clear oc0a at top
73 attiny2313/v 2543f?avr?08/04 table 36 shows the com0a1:0 bit functi onality when the wgm02:0 bits are set to phase correct pwm mode. note: 1. a special case occurs when ocr0a equ als top and com0a1 is set. in this case, the compare match is ignored, but the set or clear is done at top. see ?phase cor- rect pwm mode? on page 68 for more details.  bits 5:4 ? com0b1:0: compare match output b mode these bits control the output compare pin (oc0b) behavior. if one or both of the com0b1:0 bits are set, the oc0b output overrides the normal port functionality of the i/o pin it is connected to. ho wever, note that t he data direction register (ddr) bit cor- responding to the oc0b pin must be set in order to enable the output driver. when oc0b is connected to the pin, the func tion of the com0b1:0 bits depends on the wgm02:0 bit setting. table 37 shows the com0a1:0 bit functionality when the wgm02:0 bits are set to a normal or ctc mode (non-pwm). table 38 shows the com0b1:0 bit functionality when the wgm02:0 bits are set to fast pwm mode. note: 1. a special case occurs when ocr0b equ als top and com0b1 is set. in this case, the compare match is ignored, but the set or clear is done at top. see ?fast pwm mode? on page 67 for more details. table 36. compare output mode, phase correct pwm mode (1) com0a1 com0a0 description 0 0 normal port operation, oc0a disconnected. 0 1 wgm02 = 0: normal port operation, oc0a disconnected. wgm02 = 1: toggle oc0a on compare match. 1 0 clear oc0a on compare match when up-counting. set oc0a on compare match when down-counting. 1 1 set oc0a on compare match when up-counting. clear oc0a on compare match when down-counting. table 37. compare output mode, non-pwm mode com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 0 1 toggle oc0b on compare match 1 0 clear oc0b on compare match 1 1 set oc0b on compare match table 38. compare output mode, fast pwm mode (1) com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 01reserved 1 0 clear oc0b on compare match, set oc0b at top 1 1 set oc0b on compare match, clear oc0b at top
74 attiny2313/v 2543f?avr?08/04 table 39 shows the com0b1:0 bit functi onality when the wgm02:0 bits are set to phase correct pwm mode. note: 1. a special case occurs when ocr0b equ als top and com0b1 is set. in this case, the compare match is ignored, but the set or clear is done at top. see ?phase cor- rect pwm mode? on page 68 for more details.  bits 3, 2 ? res: reserved bits these bits are reserved bits in the attiny2313 and will a lways read as zero.  bits 1:0 ? wgm01:0: waveform generation mode combined with the wgm02 bit found in the tccr0b register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and what type of waveform generation to be used, see table 40. modes of operation sup- ported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and two types of pulse width modulation (pwm) modes (see ?modes of operation? on page 93). notes: 1. max = 0xff 2. bottom = 0x00 table 39. compare output mode, phase correct pwm mode (1) com0b1 com0b0 description 0 0 normal port operation, oc0b disconnected. 01reserved 1 0 clear oc0b on compare match when up-counting. set oc0b on compare match when down-counting. 1 1 set oc0b on compare match when up-counting. clear oc0b on compare match when down-counting. table 40. waveform generation mode bit description mode wgm2 wgm1 wgm0 timer/counter mode of operation top update of ocrx at tov flag set on (1)(2) 0 0 0 0 normal 0xff immediate max 1 0 0 1 pwm, phase correct 0xff top bottom 2 0 1 0 ctc ocra immediate max 3 0 1 1 fast pwm 0xff top max 41 0 0reserved ? ? ? 5 1 0 1 pwm, phase correct ocra top bottom 61 1 0reserved ? ? ? 7 1 1 1 fast pwm ocra top top
75 attiny2313/v 2543f?avr?08/04 timer/counter control register b ? tccr0b  bit 7 ? foc0a: force output compare a the foc0a bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatib ility with future devices, this bit must be set to zero when tccr0b is written when operating in pw m mode. when writing a logical one to the foc0a bit, an immediate compare match is forced on the waveform generation unit. the oc0a output is changed according to its com0a1:0 bits setting. note that the foc0a bit is implemented as a strobe. therefore it is the value present in the com0a1:0 bits that determines the effect of the forced compare. a foc0a strobe will not generate any interrup t, nor will it clear the timer in ctc mode using ocr0a as top. the foc0a bit is always read as zero.  bit 6 ? foc0b: force output compare b the foc0b bit is only active when the wgm bits specify a non-pwm mode. however, for ensuring compatib ility with future devices, this bit must be set to zero when tccr0b is written when operating in pw m mode. when writing a logical one to the foc0b bit, an immediate compare match is forced on the waveform generation unit. the oc0b output is changed according to its com0b1:0 bits setting. note that the foc0b bit is implemented as a strobe. therefore it is the value present in the com0b1:0 bits that determines the effect of the forced compare. a foc0b strobe will not generate any interrup t, nor will it clear the timer in ctc mode using ocr0b as top. the foc0b bit is always read as zero.  bits 5:4 ? res: reserved bits these bits are reserved bits in the attiny2313 and will a lways read as zero.  bit 3 ? wgm02: waveform generation mode see the description in the ?timer/counter control register a ? tccr0a? on page 72.  bits 2:0 ? cs02:0: clock select the three clock select bits select the cl ock source to be used by the timer/counter. see table 41 on page 76. bit 7 6 5 4 3 2 1 0 foc0a foc0b ? ? wgm02 cs02 cs01 cs00 tccr0b read/write w w r r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
76 attiny2313/v 2543f?avr?08/04 if external pin modes are used for the timer/counter0, transitions on the t0 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. timer/counter register ? tcnt0 the timer/counter register gives direct access, both for read and write operations, to the timer/counter unit 8-bit counter. writing to the tcnt0 register blocks (removes) the compare match on the following timer clock. modifying the counter (tcnt0) while the counter is running, introduces a risk of missing a compare match between tcnt0 and the ocr0x registers. output compare register a ? ocr0a the output compare register a contains an 8-bit value that is continuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0a pin. output compare register b ? ocr0b the output compare register b contains an 8-bit value that is continuously compared with the counter value (tcnt0). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc0b pin. table 41. clock select bit description cs02 cs01 cs00 description 0 0 0 no clock source (timer/counter stopped) 001clk i/o /(no prescaling) 010clk i/o /8 (from prescaler) 011clk i/o /64 (from prescaler) 100clk i/o /256 (from prescaler) 101clk i/o /1024 (from prescaler) 1 1 0 external clock source on t0 pin. clock on falling edge. 1 1 1 external clock source on t0 pin. clock on rising edge. bit 76543210 tcnt0[7:0] tcnt0 read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr0a[7:0] ocr0a read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr0b[7:0] ocr0b read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
77 attiny2313/v 2543f?avr?08/04 timer/counter interrupt mask register ? timsk  bit 4 ? res: reserved bit this bit is reserved bit in the at tiny2313 and will always read as zero.  bit 2 ? ocie0b: timer/counter0 output compare match b interrupt enable when the ocie0b bit is written to one, and the i-bit in the status register is set, the timer/counter compare match b interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter occurs, i.e., when the ocf0b bit is set in the timer/counter interrupt flag register ? tifr.  bit 1 ? toie0: timer/counter0 overflow interrupt enable when the toie0 bit is written to one, and the i-bit in the status register is set, the timer/counter0 overflow interrupt is enable d. the corresponding interrupt is executed if an overflow in timer/counter0 occurs, i.e., when the tov0 bit is set in the timer/counter 0 interrupt flag register ? tifr.  bit 0 ? ocie0a: timer/counter0 output compare match a interrupt enable when the ocie0a bit is written to one, and the i-bit in the status register is set, the timer/counter0 compare match a interrupt is enabled. the corresponding interrupt is executed if a compare match in timer/counter0 occurs, i.e., when the ocf0a bit is set in the timer/counter 0 interrupt flag register ? tifr. timer/counter interrupt flag register ? tifr  bit 4 ? res: reserved bit this bit is reserved bit in the at tiny2313 and will always read as zero.  bit 2 ? ocf0b: output compare flag 0 b the ocf0b bit is set when a compare match occurs between the timer/counter and the data in ocr0b ? output compare register0 b. ocf0b is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, ocf0b is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0b (timer/counter compare b match interrupt enable), and ocf0b are set, the timer/counter compare match interrupt is executed.  bit 1 ? tov0: timer/counter0 overflow flag the bit tov0 is set when an overflow occu rs in timer/counter0. tov0 is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, tov0 is cleared by writing a logic one to the flag. when the sreg i-bit, toie0 (timer/counter0 overflow interrupt enable), and tov0 are set, the timer/counter0 overflow interrupt is executed. the setting of this flag is dependent of the wgm02:0 bit setting. refer to table 40, ?waveform generation mode bit description? on page 74.  bit 0 ? ocf0a: output compare flag 0 a bit 76543210 toie1 ocie1a ocie1b ? icie1 ocie0b toie0 ocie0a timsk read/write r/w r/w r/w r r/w r/w r/w r/w initial value00000000 bit 76543210 tov1 ocf1a ocf1b ? icf1 ocf0b tov0 ocf0a tifr read/write r/w r/w r/w r r/w r/w r/w r/w initial value00000000
78 attiny2313/v 2543f?avr?08/04 the ocf0a bit is set when a compare match occurs between the timer/counter0 and the data in ocr0a ? output compare register0 a. ocf0a is cleared by hardware when executing the corresponding interrupt handling vector. alternatively, ocf0a is cleared by writing a logic one to the flag. when the i-bit in sreg, ocie0a (timer/counter0 compare match interrupt enable), and ocf0a are set, the timer/counter0 compare match interrupt is executed.
79 attiny2313/v 2543f?avr?08/04 timer/counter0 and timer/counter1 prescalers timer/counter1 and timer/counter0 share the same prescaler module, but the timer/counters can have different prescaler settings. the description below applies to both timer/counter1 and timer/counter0. internal clock source the timer/counter can be clocked directly by the system clock (by setting the csn2:0 = 1). this provides the fastes t operation, with a maximum timer/counter clock frequency equal to system clock frequency (f clk_i/o ). alternatively, one of four taps from the pres- caler can be used as a clock source. the prescaled clock has a frequency of either f clk_i/o /8, f clk_i/o /64, f clk_i/o /256, or f clk_i/o /1024. prescaler reset the prescaler is free running, i.e., operates independently of the clock select logic of the timer/counter, and it is shared by timer/counter1 and timer/counter0. since the prescaler is not affected by the timer/counter?s clock select, the state of the prescaler will have implications for situations where a prescaled clock is used. one example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler (6 > csn2:0 > 1). the number of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to n+1 system clock cycles, where n equals the pres- caler divisor (8, 64, 256, or 1024). it is possible to use the prescaler reset fo r synchronizing the timer/counter to program execution. however, care must be taken if the other timer/counter that shares the same prescaler also uses prescaling. a pr escaler reset will affect the prescaler period for all timer/counters it is connected to. external clock source an external clock source applied to the t1/t0 pin can be used as timer/counter clock (clk t1 /clk t0 ). the t1/t0 pin is sampled once every system clock cycle by the pin syn- chronization logic. the synchronized (sampled) signal is then passed through the edge detector. figure 37 shows a functional equivalent block diagram of the t1/t0 synchroni- zation and edge detector logic. the registers are clocked at the positive edge of the internal system clock ( clk i/o ). the latch is transparent in the high period of the internal system clock. the edge detector generates one clk t1 /clk t 0 pulse for each positive (csn2:0 = 7) or neg- ative (csn2:0 = 6) edge it detects. figure 37. t1/t0 pin sampling the synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles from an edge has been applied to the t1/t0 pin to the counter is updated. enabling and disabling of the clock input must be done when t1/t0 has been stable for at least one system clock cycle, otherwise it is a risk that a false timer/counter clock pulse is generated. each half period of the exte rnal clock applied must be longer than one system clock cycle to ensure correct sampling. the external clock must be guaranteed to have less than half the system clock frequency (f extclk < f clk_i/o /2) given a 50/50% duty cycle. since tn_sync (to clock select logic) edge detector synchronization dq dq le dq tn clk i/o
80 attiny2313/v 2543f?avr?08/04 the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling frequency (nyquist sampling theorem). however, due to vari- ation of the system clock freq uency and duty cycle caused by oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than f clk_i/o /2.5. an external clock source can not be prescaled. figure 38. prescaler for timer/counter0 and timer/counter1 (1) note: 1. the synchronization logic on the input pins ( t1/t0) is shown in figure 37. general timer/counter control register ? gtccr  bits 7..1 ? res: reserved bits these bits are reserved bits in the attiny2313 and will a lways read as zero.  bit 0 ? psr10: prescaler reset timer/counter1 and timer/counter0 when this bit is one, timer/counter1 and ti mer/counter0 prescaler will be reset. this bit is normally cleared immediately by hardware. note that timer/counter1 and timer/counter0 share the same prescaler and a reset of this pres caler will affect both timers. psr10 clear clk t1 clk t0 t1 t0 clk i/o synchronization synchronization bit 7 6 5 4 3 2 1 0 ? ? ? ? ? ? ? psr10 gtccr read/write r r r r r r r r/w initial value 0 0 0 0 0 0 0 0
81 attiny2313/v 2543f?avr?08/04 16-bit timer/counter1 the 16-bit timer/counter unit allows accura te program execution timing (event man- agement), wave generation, and signal timing measurement. the main features are:  true 16-bit design (i.e., allows 16-bit pwm)  two independent output compare units  double buffered out put compare registers  one input capture unit  input capture noise canceler  clear timer on compar e match (auto reload)  glitch-free, phase correct pu lse width modulator (pwm)  variable pwm period  frequency generator  external event counter  four independent interrupt sources (tov1, ocf1a, ocf1b, and icf1) overview most register and bit references in this se ction are written in general form. a lower case ?n? replaces the timer/counter number, and a lower case ?x? replaces the output com- pare unit channel. however, when using the register or bit defines in a program, the precise form must be used, i.e., tcnt1 for accessing timer/counter1 counter value and so on. a simplified block diagram of the 16-bit time r/counter is shown in figure 39. for the actual placement of i/o pins, refer to ?pin out attiny2313? on page 2. cpu accessible i/o registers, including i/o bits and i/o pins , are shown in bold. the device-specific i/o register and bit locations are listed in the ?16-bit timer/counter register description? on page 103. figure 39. 16-bit timer/counter block diagram (1) note: 1. refer to figure 1 on page 2 for timer/counter1 pin placement and description. clock select timer/counter data b u s ocrna ocrnb icrn = = tcntn waveform generation waveform generation ocna ocnb noise canceler icpn = fixed top values edge detector control logic = 0 top bottom count clear direction tovn (int.req.) ocna (int.req.) ocnb (int.req.) icfn (int.req.) tccrna tccrnb ( from analog comparator ouput ) tn edge detector ( from prescaler ) clk tn
82 attiny2313/v 2543f?avr?08/04 registers the timer/counter (tcnt1), output compare registers (ocr1a/b), and input capture register (icr1) are all 16-bit registers. special procedures must be followed when accessing the 16-bit registers. these procedur es are described in the section ?access- ing 16-bit registers? on page 83. the timer/counter co ntrol registers (tccr1a/b) are 8-bit registers and have no cpu access restrictions. interrupt requests (abbreviated to int.req. in the figure) signals are all visible in the timer interrupt flag register (tifr). all interrupts are individually masked with the timer interrupt mask register (timsk). tifr and timsk are not shown in the figure. the timer/counter can be clocked internally, via the prescaler, or by an external clock source on the t1 pin. the clock select logic block controls which clock source and edge the timer/counter uses to increment (or decrement) its value. the timer/counter is inactive when no cloc k source is selected. the output from the clock select logic is referred to as the timer clock (clk t 1 ). the double buffered output compare registers (ocr1a/b) are compared with the timer/counter value at all time. the result of the compare can be used by the waveform generator to generate a pwm or variable frequency output on the output compare pin (oc1a/b). see ?output compar e units? on page 90.. the compare match event will also set the compare match flag (ocf1a/b) which can be used to generate an output compare interrupt request. the input capture register can capture the timer/counter value at a given external (edge triggered) event on either the input capture pin (icp1) or on the analog compar- ator pins (see ?analog comparator? on page 148.) the input capture unit includes a digital filtering unit (noise canceler) for reducing the chance of capturing noise spikes. the top value, or maximum timer/counter value, can in some modes of operation be defined by either the ocr1a register, the icr1 register, or by a set of fixed values. when using ocr1a as top value in a pwm mode, the ocr1a register can not be used for generating a pwm output. however, the top value will in this case be double buffered allowing the top value to be changed in run time. if a fixed top value is required, the icr1 register can be used as an alternative, freeing the ocr1a to be used as pwm output. definitions the following definitions are used extensively throughout the section: compatibility the 16-bit timer/counter has been updated an d improved from previous versions of the 16-bit avr timer/counter. this 16-bit timer/counter is fully compatible with the earlier version regarding:  all 16-bit timer/counter related i/o register address locations, including timer interrupt registers.  bit locations inside all 16-b it timer/counter registers, including timer interrupt registers.  interrupt vectors. table 42. definitions bottom the counter reaches the bottom when it becomes 0x0000. max the counter reaches its max imum when it becomes 0xffff (decimal 65535). top the counter reaches the top when it becomes equal to the highest value in the count sequence. the top value can be assigned to be one of the fixed values: 0x00ff, 0x01ff, or 0x03ff, or to the value stored in the ocr1a or icr1 regis- ter. the assignment is dependent of the mode of operation.
83 attiny2313/v 2543f?avr?08/04 the following control bits have changed name, but have same functionality and register location:  pwm10 is changed to wgm10.  pwm11 is changed to wgm11.  ctc1 is changed to wgm12. the following bits are added to the 16-bit timer/counter control registers:  foc1a and foc1b are added to tccr1a.  wgm13 is added to tccr1b. the 16-bit timer/counter has improvements that will affect the compatibility in some special cases. accessing 16-bit registers the tcnt1, ocr1a/b, and icr1 are 16-bit registers that can be accessed by the avr cpu via the 8-bit data bus. the 16-bit register must be byte accessed using two read or write operations. each 16-bit timer has a single 8-bit register for temporary storing of the high byte of the 16-bit access. the same temporary register is shared between all 16-bit registers within each 16-bit timer. accessing the low byte triggers the 16-bit read or write operation. when the low byte of a 16-bit register is written by the cpu, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. when the low byte of a 16-bit register is read by the cpu, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. not all 16-bit accesses uses the temporary register for the high byte. reading the ocr1a/b 16-bit registers does not involve using the temporary register. to do a 16-bit write, the high byte must be written before the low byte. for a 16-bit read, the low byte must be read before the high byte. the following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the temporary register. the same principle can be used directly for accessing the ocr1a/b and icr1 registers. note that when using ?c?, the compiler handles the 16-bit access.
84 attiny2313/v 2543f?avr?08/04 note: 1. the example code assumes that th e part specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?s bis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. the assembly code example returns the tcnt1 value in the r17:r16 register pair. it is important to notice that accessing 16-bit registers are atomic operations. if an inter- rupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit timer registers, then the re sult of the access outside the interrupt will be corrupted. therefore, when both the main code and the interrupt code update the temporary regis- ter, the main code must disable the interrupts during the 16-bit access. assembly code examples (1) ... ; set tcnt 1 to 0x01ff ldi r17,0x01 ldi r16,0xff out tcnt 1 h,r17 out tcnt 1 l,r16 ; read tcnt 1 into r17:r16 in r16,tcnt 1 l in r17,tcnt 1 h ... c code examples (1) unsigned int i; ... /* set tcnt 1 to 0x01ff */ tcnt 1 = 0x1ff; /* read tcnt 1 into i */ i = tcnt 1 ; ...
85 attiny2313/v 2543f?avr?08/04 the following code examples show how to do an atomic read of the tcnt1 register contents. reading any of the ocr1a/b or icr1 registers can be done by using the same principle. note: 1. the example code assumes that th e part specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?s bis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. the assembly code example returns the tcnt1 value in the r17:r16 register pair. assembly code example (1) tim16_readtcnt 1 : ; save global interrupt flag in r18,sreg ; disable interrupts cli ; read tcnt 1 into r17:r16 in r16,tcnt 1 l in r17,tcnt 1 h ; restore global interrupt flag out sreg,r18 ret c code example (1) unsigned int tim16_readtcnt 1 ( void ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ __disable_interrupt(); /* read tcnt 1 into i */ i = tcnt 1 ; /* restore global interrupt flag */ sreg = sreg; return i; }
86 attiny2313/v 2543f?avr?08/04 the following code examples show how to do an atomic write of the tcnt1 register contents. writing any of the ocr1a/b or icr1 registers can be done by using the same principle. note: 1. the example code assumes that th e part specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?s bis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. the assembly code example requires that the r17:r16 register pair contains the value to be written to tcnt1. reusing the temporary high byte register if writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. however, note that the same rule of atomic operation described pr eviously also applies in this case. assembly code example (1) tim16_writetcnt 1 : ; save global interrupt flag in r18,sreg ; disable interrupts cli ; set tcnt 1 to r17:r16 out tcnt 1 h,r17 out tcnt 1 l,r16 ; restore global interrupt flag out sreg,r18 ret c code example (1) void tim16_writetcnt 1 ( unsigned int i ) { unsigned char sreg; unsigned int i; /* save global interrupt flag */ sreg = sreg; /* disable interrupts */ __disable_interrupt(); /* set tcnt 1 to i */ tcnt 1 = i; /* restore global interrupt flag */ sreg = sreg; }
87 attiny2313/v 2543f?avr?08/04 timer/counter clock sources the timer/counter can be clocked by an intern al or an external clock source. the clock source is selected by the clock sele ct logic which is controlled by the clock select (cs12:0) bits located in the timer/counter cont rol register b (tccr1b). for details on clock sources and pre scaler, see ?timer/counter0 and timer/counter1 prescalers? on page 79. counter unit the main part of the 16-bit timer/counter is the programmable 16-bit bi-directional counter unit. figure 40 shows a block diagram of the counter and its surroundings. figure 40. counter unit block diagram signal description (internal signals): count increment or decrement tcnt1 by 1. direction select between increment and decrement. clear clear tcnt1 (set all bits to zero). clk t 1 timer/counter clock. top signalize that tcnt1 has reached maximum value. bottom signalize that tcnt1 has reached minimum value (zero). the 16-bit counter is mapped into two 8-bit i/o memory locations: counter high (tcnt1h) containing the upper eight bits of the counter, and counter low (tcnt1l) containing the lower eight bits. the tcnt1h register can only be indirectly accessed by the cpu. when the cpu does an access to the tcnt1h i/o location, the cpu accesses the high byte temporary register (temp). the temporary register is updated with the tcnt1h value when the tcnt1l is read, and tcnt1h is updated with the temporary register value when tcnt1l is writ ten. this allows the cpu to read or write the entire 16-bit counter value within one cl ock cycle via the 8-bit data bus. it is impor- tant to notice that there are special cases of writing to the tcnt1 register when the counter is counting that will give unpredictable results. the special cases are described in the sections where they are of importance. depending on the mode of operation used, the counter is cleared, incremented, or dec- remented at each timer clock (clk t 1 ). the clk t 1 can be generated from an external or internal clock source, selected by the clock select bits (cs12:0). when no clock source is selected (cs12:0 = 0) the timer is stopped. however, the tcnt1 value can be accessed by the cpu, independent of whether clk t 1 is present or not. a cpu write over- rides (has priority over) all counter clear or count operations. the counting sequence is determined by the setting of the waveform generation mode bits (wgm13:0) located in the timer/counter control registers a and b (tccr1a and tccr1b). there are close connections between how the counter behaves (counts) and temp (8-bit) data bus (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) control logic count clear direction tovn (int.req.) clock select top bottom tn edge detector ( from prescaler ) clk tn
88 attiny2313/v 2543f?avr?08/04 how waveforms are generated on the output compare outputs oc1x. for more details about advanced counting sequences and waveform generation, see ?modes of opera- tion? on page 93. the timer/counter overflow flag (tov1) is set according to the mode of operation selected by the wgm13:0 bits. tov1 can be used for generating a cpu interrupt. input capture unit the timer/counter incorporates an input capt ure unit that can capture external events and give them a time-stamp indicating time of occurrence. the external signal indicating an event, or multiple events, can be applied via the icp1 pin or alternatively, via the analog-comparator unit. the time-stamps c an then be used to calculate frequency, duty- cycle, and other features of the signal a pplied. alternatively the time-stamps can be used for creating a log of the events. the input capture unit is illustrated by the block diagram shown in figure 41. the ele- ments of the block diagram that are not directly a part of the input capture unit are gray shaded. the small ?n? in register and bit names indicates the timer/counter number. figure 41. input capture unit block diagram when a change of the logic level (an event) occurs on the input capture pin (icp1), alternatively on the analog comparator output (aco), and this change confirms to the setting of the edge de tector, a capture will be triggered. when a captur e is triggered, the 16-bit value of the counter (tcnt1) is written to the input capture register (icr1). the input capture flag (icf1) is set at the same system clock as the tcnt1 value is copied into icr1 register. if enabled (icie1 = 1), the input capture flag generates an input capture interrupt. the icf1 flag is automatically cleared when the interrupt is executed. alternatively the icf1 flag can be cleared by so ftware by writing a logical one to its i/o bit location. reading the 16-bit value in the input capture register (icr1) is done by first reading the low byte (icr1l) and then the high byte (icr1h). when the low byte is read the high byte is copied into the high byte tempor ary register (temp). when the cpu reads the icr1h i/o location it will a ccess the temp register. icfn (int.req.) analog comparator write icrn (16-bit register) icrnh (8-bit) noise canceler icpn edge detector temp (8-bit) data bus (8-bit) icrnl (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) acic* icnc ices aco*
89 attiny2313/v 2543f?avr?08/04 the icr1 register can only be written when using a waveform generation mode that utilizes the icr1 register for defining the counter?s top value. in these cases the waveform generation mode (wgm13:0) bits must be set before the top value can be written to the icr1 register. when writing the icr1 register the high byte must be writ- ten to the icr1h i/o location before the low byte is written to icr1l. for more information on how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 83. input capture trigger source the main trigger source for the input capture unit is the input capture pin (icp1). timer/counter1 can alternatively use the a nalog comparator output as trigger source for the input capture unit. the analog comparat or is selected as trigger source by set- ting the analog comparator input capture (acic) bit in the analog comparator control and status register (acsr). be aware that changing trigger source can trigger a cap- ture. the input capture flag must therefore be cleared after the change. both the input capture pin (icp1) and the analog comparator output (aco) inputs are sampled using the same technique as for the t1 pin (figure 37 on page 79). the edge detector is also identical. ho wever, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increases the delay by four system clock cycles. note that the input of the noise canceler and edge detector is always enabled unless the timer/counter is set in a waveform generation mode that uses icr1 to define top. an input capture can be triggered by software by contro lling the port of the icp1 pin. noise canceler the noise canceler improves noise immunity by using a simple digital filtering scheme. the noise canceler input is monitored over four samples, and all four must be equal for changing the output that in turn is used by the edge detector. the noise canceler is enabled by setting the input capture noise canceler (icnc1) bit in timer/counter cont rol register b (tccr1b). when enabled the noise canceler intro- duces additional four system clock cycles of delay from a change applied to the input, to the update of the icr1 register. the noise canceler uses the system clock and is there- fore not affected by the prescaler. using the input capture unit the main challenge when using the input capture unit is to assign enough processor capacity for handling the incoming events. the time between two events is critical. if the processor has not read the captured value in the icr1 register before the next event occurs, the icr1 will be overwritten with a new va lue. in this case the result of the cap- ture will be incorrect. when using the input capture interrupt, the icr1 register should be read as early in the interrupt handler routine as possible. even though the input capture interrupt has rela- tively high priority, the maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests. using the input capture unit in any mode of operation when the top value (resolution) is actively changed during operation, is not recommended. measurement of an external signal?s duty cycle requires that the trigger edge is changed after each capture. changing the edge sensing must be done as early as possible after the icr1 register has been read. after a change of the edge, the input capture flag (icf1) must be cleared by software (writing a logical one to the i/o bit location). for measuring frequency only, the clearing of the icf1 flag is not required (if an interrupt handler is used).
90 attiny2313/v 2543f?avr?08/04 output compare units the 16-bit comparator continuously compares tcnt1 with the output compare regis- ter (ocr1x). if tcnt equals ocr1x the comparator signals a match. a match will set the output compare flag (ocf1x) at the next timer clock cycle . if enabled (ocie1x = 1), the output compare flag generates an output compare interrupt. the ocf1x flag is automatically cleared when the interrupt is executed. alternatively the ocf1x flag can be cleared by software by writing a logical one to its i/o bit location. the waveform gen- erator uses the match signal to generate an output according to operating mode set by the waveform generation mode (wgm13:0) bits and compare output mode (com1x1:0) bits. the top and bottom signals are used by the waveform generator for handling the special cases of the extreme values in some modes of operation (see ?modes of operation? on page 93.) a special feature of output compare unit a allows it to define the timer/counter top value (i.e., counter resolution). in addition to the counter resolution, the top value defines the period time for waveforms generated by the waveform generator. figure 42 shows a block diagram of the output compare unit. the small ?n? in the regis- ter and bit names indicates the device number (n = 1 for timer/counter 1), and the ?x? indicates output compare unit (a/b). the elements of the block diagram that are not directly a part of the output compare unit are gray shaded. figure 42. output compare unit, block diagram the ocr1x register is double buffered when using any of the twelve pulse width mod- ulation (pwm) modes. for the normal and clear timer on compare (ctc) modes of operation, the double buffering is disabled. the double buffering synchronizes the update of the ocr1x compare register to either top or bottom of the counting sequence. the synchronization prevents the occurrence of odd-length, non-symmetrical pwm pulses, thereby making the output glitch-free. the ocr1x register access may seem comple x, but this is not case. when the double buffering is enabled, the cpu has access to the ocr1x buffer register, and if double buffering is disabled the cpu will access the ocr1x directly. the co ntent of the ocr1x ocfnx (int.req.) = (16-bit comparator ) ocrnx buffer (16-bit register) ocrnxh buf. (8-bit) ocnx temp (8-bit) data bus (8-bit) ocrnxl buf. (8-bit) tcntn (16-bit counter) tcntnh (8-bit) tcntnl (8-bit) comnx1:0 wgmn3:0 ocrnx (16-bit register) ocrnxh (8-bit) ocrnxl (8-bit) waveform generator top bottom
91 attiny2313/v 2543f?avr?08/04 (buffer or compare) register is only changed by a write operation (the timer/counter does not update this register automatically as the tcnt1 and icr1 register). therefore ocr1x is not read via the high byte temporary register (temp). however, it is a good practice to read the low byte first as when accessing other 16-bit registers. writing the ocr1x registers must be done via the temp register since the compare of all 16 bits is done continuously. the high by te (ocr1xh) has to be written first. when the high byte i/o location is written by the cpu, the temp register will be updated by the value written. then when the low by te (ocr1xl) is written to the lower eight bits, the high byte will be copied into the upper 8-bits of either the ocr1x buffer or ocr1x compare reg- ister in the same system clock cycle. for more information of how to access the 16-bit registers refer to ?accessing 16-bit registers? on page 83. force output compare in non-pwm waveform generation modes, the match output of the comparator can be forced by writing a one to the force output compare (foc1x) bit. forcing compare match will not set the ocf1x flag or reload /clear the timer, but the oc1x pin will be updated as if a real compare match had occurred (the com11:0 bits settings define whether the oc1x pin is set, cleared or toggled). compare match blocking by tcnt1 write all cpu writes to the tcnt1 register will bl ock any compare match that occurs in the next timer clock cycle, even when the timer is stopped. this feature allows ocr1x to be initialized to the same value as tcnt1 without triggering an interrupt when the timer/counter clock is enabled. using the output compare unit since writing tcnt1 in any mode of operat ion will block all compare matches for one timer clock cycle, there are risks involved when changing tcnt1 when using any of the output compare channels, independent of whether the timer/counter is running or not. if the value written to tcnt1 equals th e ocr1x value, the compare match will be missed, resulting in incorrect waveform generation. do not write the tcnt1 equal to top in pwm modes with variable top valu es. the compare match for the top will be ignored and the counter will cont inue to 0xffff. sim ilarly, do not writ e the tcnt1 value equal to bottom when the counter is downcounting. the setup of the oc1x should be performed before setting the data direction register for the port pin to output. the easiest way of setting the oc1x value is to use the force output compare (foc1x) strobe bits in normal mode. the oc1x register keeps its value even when changing between waveform generation modes. be aware that the com1x1:0 bits are not double buffered together with the compare value. changing the com1x1:0 bi ts will take effect immediately.
92 attiny2313/v 2543f?avr?08/04 compare match output unit the compare output mode (com1x1:0) bits have two functions. the waveform gener- ator uses the com1x1:0 bits for defining the output compare (oc1x) state at the next compare match. secondly the com1x1:0 bits control the oc1x pin output source. fig- ure 43 shows a simplified schematic of the logic affected by the com1x1:0 bit setting. the i/o registers, i/o bits, and i/o pins in the figure are shown in bold. only the parts of the general i/o port control registers (ddr and port) that are affected by the com1x1:0 bits are shown. when referring to the oc1x state, the reference is for the internal oc1x register, not the oc1x pin. if a system reset occur, the oc1x register is reset to ?0?. figure 43. compare match output unit, schematic the general i/o port function is overridden by the output compare (oc1x) from the waveform generator if either of the com1x1:0 bits are set. however, the oc1x pin direction (input or output ) is still controlled by the data direction register (ddr) for the port pin. the data direction register bit for the oc1x pin (ddr_oc1x) must be set as output before the oc1x value is visible on th e pin. the port override function is generally independent of the waveform generation mode, but there are some exceptions. refer to table 43, table 44 and table 45 for details. the design of the output compare pin logic allows initialization of the oc1x state before the output is enabled. note that some com1x1:0 bit settings are reserved for certain modes of operation. see ?16-bit timer/counter register description? on page 103. the com1x1:0 bits have no effect on the input capture unit. port ddr dq dq ocnx pin ocnx dq waveform generator comnx1 comnx0 0 1 data b u s focnx clk i/o
93 attiny2313/v 2543f?avr?08/04 compare output mode and waveform generation the waveform generator uses the com1x1:0 bits differently in normal, ctc, and pwm modes. for all modes, setting the com1x1:0 = 0 tells the waveform generator that no action on the oc1x register is to be performed on the next compare match. for com- pare output actions in the non-pwm modes refer to table 43 on page 103. for fast pwm mode refer to table 44 on page 103, and for phase correct and phase and fre- quency correct pwm refer to table 45 on page 104. a change of the com1x1:0 bits state will have effect at the first co mpare match after the bits are written. for non-pwm modes, the action can be forced to have immediate effect by using the foc1x strobe bits. modes of operation the mode of operation, i.e., the behavior of the timer/counter and the output compare pins, is defined by the combination of the waveform generation mode (wgm13:0) and compare output mode (com1x1:0) bits. the compare output mode bits do not affect the counting sequence, while the waveform generation mode bits do. the com1x1:0 bits control whether the pwm output generated should be inverted or not (inverted or non-inverted pwm). for non-pwm modes the com1x1:0 bits control whether the out- put should be set, cleared or toggle at a compare match (see ?compare match output unit? on page 92.) for detailed timing information refer to ?timer/counter timing diagrams? on page 101. normal mode the simplest mode of operation is the normal mode (wgm13:0 = 0). in this mode the counting direction is always up (incrementing), and no counter clear is performed. the counter simply overruns when it passes its maximum 16-bit value (max = 0xffff) and then restarts from the bottom (0x0000). in normal operation the timer/counter over- flow flag (tov1) will be set in the same time r clock cycle as the tcnt1 becomes zero. the tov1 flag in this case behaves like a 17th bit, except that it is only set, not cleared. however, combined with the timer overflow interrupt that automatically clears the tov1 flag, the timer resolution can be increased by software. there are no special cases to consider in the normal mode, a new counter value can be written anytime. the input capture unit is easy to use in normal mode. however, observe that the maxi- mum interval between the external events must not exceed the resolution of the counter. if the interval between events are too long, the timer overflow interrupt or the prescaler must be used to extend the resolution for the capture unit. the output compare units can be used to generate interrupts at some given time. using the output compare to generate waveforms in normal mode is not recommended, since this will occupy too much of the cpu time. clear timer on compare match (ctc) mode in clear timer on compare or ctc mode (wgm13:0 = 4 or 12), the ocr1a or icr1 register are used to manipulate the counte r resolution. in ctc mode the counter is cleared to zero when the counter value (tcnt1) matches either the ocr1a (wgm13:0 = 4) or the icr1 (wgm13:0 = 12). the ocr1a or icr1 define the top value for the counter, hence also its resolution. this mode allows greater control of the compare match output frequency. it also simplifies th e operation of counting external events. the timing diagram for the ctc mode is shown in figure 44 on page 94. the counter value (tcnt1) increase s until a compare match occurs with either ocr1a or icr1, and then counter (tcnt1) is cleared.
94 attiny2313/v 2543f?avr?08/04 figure 44. ctc mode, timing diagram an interrupt can be generated at each time the counter value reaches the top value by either using the ocf1a or icf1 flag according to the register used to define the top value. if the interrupt is enabled, the interrupt handler routine can be used for updating the top value. however, changing the top to a value close to bottom when the counter is running with none or a low prescaler value must be done with care since the ctc mode does not have the double buffering feature. if the new value written to ocr1a or icr1 is lower than the current value of tcnt1, the counter will miss the com- pare match. the counter will then have to count to its maximum value (0xffff) and wrap around starting at 0x0000 before the compare match can occur. in many cases this feature is not desirable. an alternative will then be to use the fast pwm mode using ocr1a for defining top (wgm13:0 = 15) since the ocr1a then will be double buffered. for generating a waveform output in ctc mode, the oc1a output can be set to toggle its logical level on each compare match by setting the compare output mode bits to tog- gle mode (com1a1:0 = 1). the oc1a value w ill not be visible on the port pin unless the data direction for the pin is set to output (ddr_oc1a = 1). the waveform generated will have a maximum frequency of f oc 1 a = f clk_i/o /2 when ocr1a is set to zero (0x0000). the waveform frequency is defined by the following equation: the n variable represents the prescaler factor (1, 8, 64, 256, or 1024). as for the normal mode of operation, the tov1 flag is set in the same timer clock cycle that the counter counts from max to 0x0000. tcntn ocna (toggle) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 4 period 2 3 (comna1:0 = 1) f ocna f clk_i/o 2 n 1 ocrna + () ?? -------------------------------------------------- - =
95 attiny2313/v 2543f?avr?08/04 fast pwm mode the fast pulse width modulation or fast pwm mode (wgm13:0 = 5, 6, 7, 14, or 15) pro- vides a high frequency pwm waveform generation option. the fast pwm differs from the other pwm options by its single-slope operation. the counter counts from bottom to top then restarts from bottom. in non-inverting compare output mode, the output compare (oc1x) is set on the compare match between tcnt1 and ocr1x, and cleared at top. in inverting compare output mode output is cleared on compare match and set at top. due to the single-slope operation, the operating frequency of the fast pwm mode can be twice as high as the phase correct and phase and frequency correct pwm modes that use dual-slope operation. this high frequency makes the fast pwm mode well suited for power regulation, re ctification, and dac applications. high fre- quency allows physically sm all sized external components (coils, capacitors), hence reduces total system cost. the pwm resolution for fast pwm can be fixed to 8-, 9-, or 10-bit, or defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution in bits can be calculated by using the following equation: in fast pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgm13:0 = 5, 6, or 7), the value in icr1 (wgm13:0 = 14), or th e value in ocr1a (wgm13:0 = 15). the counter is then cleared at the following timer clock cycle. the timing diagram for the fast pwm mode is shown in figure 45. the figure shows fast pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the ti ming diagram shown as a histogram for illus- trating the single-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt1 slopes represent compare matches between ocr1x and tcnt1. the oc1x interrupt flag will be set when a com- pare match occurs. figure 45. fast pwm mode, timing diagram the timer/counter overflow flag (tov1) is set each time the counter reaches top. in addition the oc1a or icf1 flag is set at t he same timer clock cycle as tov1 is set when either ocr1a or icr1 is used for defining the top value. if one of the interrupts are enabled, the interrupt handler routine can be used for updating the top and compare values. r fpwm top 1 + () log 2 () log ---------------------------------- - = tcntn ocrnx/top update and tovn interrupt flag set and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 7 period 2 3 4 5 6 8 ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
96 attiny2313/v 2543f?avr?08/04 when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcnt1 and the ocr1x. note that when using fixed top values the unused bits are masked to zero when any of the ocr1x registers are written. the procedure for updating icr1 differs from updating ocr1a when used for defining the top value. the icr1 register is not dou ble buffered. this means that if icr1 is changed to a low value when the counter is running with none or a low prescaler value, there is a risk that the new icr1 value written is lower than the current value of tcnt1. the result will then be that the counter will miss the comp are match at the top value. the counter will then have to count to t he max value (0xffff) and wrap around start- ing at 0x0000 before the compare match can occur. the ocr1a register however, is double buffered. this feature allows the ocr1a i/o location to be written anytime. when the ocr1a i/o location is written the value written will be put into the ocr1a buffer register. the ocr1a compare register will then be updated with the value in the buffer register at the next timer clo ck cycle the tcnt1 matches top. the update is done at the same timer clock cycle as the tcnt1 is cleared and the tov1 flag is set. using the icr1 register for defining top works well when using fixed top values. by using icr1, the ocr1a register is free to be used for generating a pwm output on oc1a. however, if the base pwm frequency is actively changed (by changing the top value), using the ocr1a as top is clearly a better choice due to its double buffer feature. in fast pwm mode, the compare units allow generation of pwm waveforms on the oc1x pins. setting the com1x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1x1:0 to three (see table 43 on page 103). the actual oc1x value will only be visible on the port pin if the data direc- tion for the port pin is set as output (ddr_oc1x). the pwm waveform is generated by setting (or clearing) the oc1x register at the compare match between ocr1x and tcnt1, and clearing (or setting) the oc1x register at the timer clock cycle the counter is cleared (changes from top to bottom). the pwm frequency for the output can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocr1x register represents special cases when generating a pwm waveform output in the fast pwm mode. if the ocr1x is set equal to bottom (0x0000) the output will be a na rrow spike for each top+1 timer clock cycle. setting the ocr1x equal to top will result in a constant high or low output (depending on the polar- ity of the output set by the com1x1:0 bits.) a frequency (with 50% duty cycle) waveform output in fast pwm mode can be achieved by setting oc1a to toggle its logical level on each compare match (com1a1:0 = 1). the waveform generated will have a maximum frequency of f oc 1 a = f clk_i/o /2 when ocr1a is set to zero (0x0000). this feat ure is similar to the oc1a t oggle in ctc mode, except the double buffer feature of the output compare unit is enabled in the fast pwm mode. f ocnxpwm f clk_i/o n 1 top + () ? ---------------------------------- - =
97 attiny2313/v 2543f?avr?08/04 phase correct pwm mode the phase correct pulse width modulation or phase correct pwm mode (wgm13:0 = 1, 2, 3, 10, or 11) provides a high resolution phase correct pwm waveform generation option. the phase correct pwm mode is, like the phase and frequency correct pwm mode, based on a dual-slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bottom. in non-inverting compare output mode, the output compare (oc1x) is cleared on the compare match between tcnt1 and ocr1x while upcounting, and set on the compare match while downcounting. in inverting output compare mode, the operation is inverted. the dual-slope operation has lower maximum operation frequency than single slope operation. however, due to the symmetric feature of the dual-slope pwm modes, these modes are preferred for motor control applications. the pwm resolution for the phase correct pwm mode can be fixed to 8-, 9-, or 10-bit, or defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution in bits can be calculated by using the following equation: in phase correct pwm mode the counter is incremented until the counter value matches either one of the fixed values 0x00ff, 0x01ff, or 0x03ff (wgm13:0 = 1, 2, or 3), the value in icr1 (wgm13:0 = 10 ), or the value in ocr1a (wgm13:0 = 11). the counter has then reached the top and changes the count direction. the tcnt1 value will be equal to top for one timer clock cycle. the timing diagram for the phase correct pwm mode is shown on figure 46. the figure shows phase correct pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the di agram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt1 slopes repre- sent compare matches between ocr1x and tc nt1. the oc1x interrupt flag will be set when a compare match occurs. figure 46. phase correct pwm mode, timing diagram the timer/counter overflow flag (tov1) is set each time the counter reaches bot- tom. when either ocr1a or icr1 is used for defining the top value, the oc1a or r pcpwm top 1 + () log 2 () log ---------------------------------- - = ocrnx/top update and ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 2 3 4 tovn interrupt flag set (interrupt on bottom) tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
98 attiny2313/v 2543f?avr?08/04 icf1 flag is set accordingly at the same timer clock cycle as the ocr1x registers are updated with the double buffer value (at top). the interrupt flags can be used to gener- ate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcnt1 and the ocr1x. note that when using fixed top values, the unused bits are masked to zero when any of the ocr1x registers are written. as the third period shown in figure 46 illustrates, changing the top ac tively while the timer/ counter is running in the phase correct mode can result in an unsymmetrical output. the reason for this can be found in the time of update of the ocr1x register. since the ocr1x update occurs at top, the pwm period starts and ends at top. this implies that the length of the fall- ing slope is determined by the previous top value, while the length of the rising slope is determined by the new top value. when these two values differ the two slopes of the period will differ in length. the difference in length gives the unsymme trical result on the output. it is recommended to use the phase and frequency correct mode instead of the phase correct mode when changing the top value wh ile the timer/counter is running. when using a static top value there are practically no differences between the two modes of operation. in phase correct pwm mode, the compare units allow generation of pwm waveforms on the oc1x pins. setting the com1x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1x1:0 to three (see table 44 on page 103). the actual oc1x value will only be visible on the port pin if the data direction for the port pin is set as out put (ddr_oc1x). the pwm waveform is gener- ated by setting (or clearing) the oc1x regi ster at the compare match between ocr1x and tcnt1 when the counter increments, and clearing (or setting) the oc1x register at compare match between ocr1x and tcnt1 when the counter decrements. the pwm frequency for the output when using phase correct pwm can be calculated by the fol- lowing equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocr1x register represent special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr1x is set equal to bottom the output will be continuously low and if set equal to top the output will be continuously high for non-inverted pwm mode. for inverted pw m the output will have the opposite logic values. f ocnxpcpwm f clk_i/o 2 ntop ?? --------------------------- - =
99 attiny2313/v 2543f?avr?08/04 phase and frequency correct pwm mode the phase and frequency correct pulse width modulation, or phase and frequency cor- rect pwm mode (wgm13:0 = 8 or 9) provides a high resolution phase and frequency correct pwm waveform generation option. the phase and frequency correct pwm mode is, like the phase correct pwm mode, based on a dual-slope operation. the counter counts repeatedly from bottom (0x0000) to top and then from top to bot- tom. in non-inverting compare output mode, the output compare (oc1x) is cleared on the compare match between tcnt1 and ocr1x while upcounting, and set on the compare match while downcounting. in inverting compare output mode, the operation is inverted. the dual-slope operation gives a lower maximum operation frequency com- pared to the single-slope operation. however, due to the symmetric feature of the dual- slope pwm modes, these modes are preferred for motor control applications. the main difference between the phase correct, and the phase and frequency correct pwm mode is the time the ocr1x register is updated by the ocr1x buffer register, (see figure 46 and figure 47). the pwm resolution for the phase and frequency correct pwm mode can be defined by either icr1 or ocr1a. the minimum resolution allowed is 2-bit (icr1 or ocr1a set to 0x0003), and the maximum resolution is 16-bit (icr1 or ocr1a set to max). the pwm resolution in bits can be calculated using the following equation: in phase and frequency correct pwm mode the counter is incremented until the counter value matches either the value in icr1 (wgm13:0 = 8), or the value in ocr1a (wgm13:0 = 9). the counter has then reached the top and changes the count direc- tion. the tcnt1 value will be equal to top for one ti mer clock cycle. the timing diagram for the phase correct and frequency correct pwm mode is shown on figure 47. the figure shows phase and frequency correct pwm mode when ocr1a or icr1 is used to define top. the tcnt1 value is in the timing diagram shown as a histogram for illustrating the dual-slope operation. the diagram includes non-inverted and inverted pwm outputs. the small horizontal line marks on the tcnt1 slopes represent compare matches between ocr1x and tcnt1. the oc1x interrupt flag will be set when a com- pare match occurs. figure 47. phase and frequency correct pwm mode, timing diagram r pfcpwm top 1 + () log 2 () log ---------------------------------- - = ocrnx/top updateand tovn interrupt flag set (interrupt on bottom) ocna interrupt flag set or icfn interrupt flag set (interrupt on top) 1 2 3 4 tcntn period ocnx ocnx (comnx1:0 = 2) (comnx1:0 = 3)
100 attiny2313/v 2543f?avr?08/04 the timer/counter overflow flag (tov1) is set at the same timer clock cycle as the ocr1x registers are updated with the double buffer value (at bottom). when either ocr1a or icr1 is used for defining the top value, the oc1a or icf1 flag set when tcnt1 has reached top. the interrupt flags can then be used to generate an interrupt each time the counter reaches the top or bottom value. when changing the top value the program must ensure that the new top value is higher or equal to the value of all of the compare registers. if the top value is lower than any of the compare registers, a compare match will never occur between the tcnt1 and the ocr1x. as figure 47 shows the output generated is, in contrast to the phase correct mode, sym- metrical in all periods. since the ocr1x registers are updated at bottom, the length of the rising and the falling slopes will always be equal. this gives symmetrical output pulses and is therefore frequency correct. using the icr1 register for defining top works well when using fixed top values. by using icr1, the ocr1a register is free to be used for generating a pwm output on oc1a. however, if the base pwm frequency is actively changed by changing the top value, using the ocr1a as top is clearl y a better choice due to its double buffer feature. in phase and frequency correct pwm mode, the compare units allow generation of pwm waveforms on the oc1x pins. setting the com1x1:0 bits to two will produce a non-inverted pwm and an inverted pwm output can be generated by setting the com1x1:0 to three (see table 45 on page 104). the actual oc1x value will only be vis- ible on the port pin if the data direction for the port pin is set as output (ddr_oc1x). the pwm waveform is generated by setting (or clearing) the oc1x register at the compare match between ocr1x and tcnt1 when the counter increments, and clearing (or set- ting) the oc1x register at compare match between ocr1x and tcnt1 when the counter decrements. the pwm frequency for the output when using phase and fre- quency correct pwm can be calculated by the following equation: the n variable represents the prescaler divider (1, 8, 64, 256, or 1024). the extreme values for the ocr1x register represents special cases when generating a pwm waveform output in the phase correct pwm mode. if the ocr1x is set equal to bottom the output will be continuously low and if set equal to top the output will be set to high for non-inverted pwm mode. for inverted pwm the output will have the opposite logic values. f ocnxpfcpwm f clk_i/o 2 ntop ?? --------------------------- - =
101 attiny2313/v 2543f?avr?08/04 timer/counter timing diagrams the timer/counter is a synchronous design and the timer clock (clk t1 ) is therefore shown as a clock enable signal in the followi ng figures. the figures include information on when interrupt flags are set, and when the ocr1x register is updated with the ocr1x buffer value (only for mo des utilizing double buffering ). figure 48 shows a timing diagram for the setting of ocf1x. figure 48. timer/counter timing diagram, setting of ocf1x, no prescaling figure 49 shows the same timing data, but with the prescaler enabled. figure 49. timer/counter timing diagram, setting of ocf1x, with prescaler (f clk_i/o /8) figure 50 shows the count sequence close to top in various modes. when using phase and frequency correct pwm mode the ocr1x register is updated at bottom. the timing diagrams will be th e same, but top should be replaced by bottom, top-1 by bottom+1 and so on. the same renaming applies for modes that set the tov1 flag at bottom. clk tn (clk i/o /1) ocfnx clk i/o ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 ocfnx ocrnx tcntn ocrnx value ocrnx - 1 ocrnx ocrnx + 1 ocrnx + 2 clk i/o clk tn (clk i/o /8)
102 attiny2313/v 2543f?avr?08/04 figure 50. timer/counter timing diagram, no prescaling figure 51 shows the same timing data, but with the prescaler enabled. figure 51. timer/counter timing diagram, with prescaler (f clk_i/o /8) tovn (fpwm) and icfn (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk tn (clk i/o /1) clk i/o tovn (fpwm) and icf n (if used as top) ocrnx (update at top) tcntn (ctc and fpwm) tcntn (pc and pfc pwm) top - 1 top top - 1 top - 2 old ocrnx value new ocrnx value top - 1 top bottom bottom + 1 clk i/o clk tn (clk i/o /8)
103 attiny2313/v 2543f?avr?08/04 16-bit timer/counter register description timer/counter1 control register a ? tccr1a  bit 7:6 ? com1a1:0: compare output mode for channel a  bit 5:4 ? com1b1:0: compare output mode for channel b the com1a1:0 and com1b1:0 control the output compare pins (oc1a and oc1b respectively) behavior. if one or both of t he com1a1:0 bits are written to one, the oc1a output overrides the normal port functionality of the i/o pin it is connected to. if one or both of the com1b1:0 bit are written to one, the oc1b output overrides the normal port functionality of the i/o pin it is connected to. however, note that the data direction reg- ister (ddr) bit corresponding to the oc1a or oc1b pin must be set in order to enable the output driver. when the oc1a or oc1b is connected to the pin, the function of the com1x1:0 bits is dependent of the wgm13:0 bits setting. table 43 shows the com1x1:0 bit functionality when the wgm13:0 bits are set to a normal or a ctc mode (non-pwm). table 44 shows the com1x1:0 bit functionalit y when the wgm13:0 bits are set to the fast pwm mode. note: 1. a special case occurs when ocr1a/ocr1b equals top and com1a1/com1b1 is set. in this case the compare match is ig nored, but the set or clear is done at top. see ?fast pwm mode? on page 95. for more details. bit 7 6 5 4 3210 com1a1 com1a0 com1b1 com1b0 ? ? wgm11 wgm10 tccr1a read/write r/w r/w r/w r/w r r r/w r/w initial value 0 0 0 0 0 0 0 0 table 43. compare output mode, non-pwm com1a1/com1b1 com1a0/com1b0 description 0 0 normal port operation, oc1a/oc1b disconnected. 0 1 toggle oc1a/oc1b on compare match. 1 0 clear oc1a/oc1b on compare match (set output to low level). 1 1 set oc1a/oc1b on com pare match (set output to high level). table 44. compare output mode, fast pwm (1) com1a1/com1b1 com1a0/com1b0 description 0 0 normal port operation, oc1a/oc1b disconnected. 0 1 wgm13=0: normal port operation, oc1a/oc1b disconnected. wgm13=1: toggle oc1a on compare match, oc1b reserved. 1 0 clear oc1a/oc1b on compare match, set oc1a/oc1b at top 1 1 set oc1a/oc1b on compare match, clear oc1a/oc1b at top
104 attiny2313/v 2543f?avr?08/04 table 45 shows the com1x1:0 bit functionalit y when the wgm13:0 bits are set to the phase correct or the phase and frequency correct, pwm mode. note: 1. a special case occurs when ocr1a/ocr1b equals top and com1a1/com1b1 is set. see ?phase correct pwm mode? on page 97. for more details.  bit 1:0 ? wgm11:0: waveform generation mode combined with the wgm13:2 bits found in the tccr1b register, these bits control the counting sequence of the counter, the source for maximum (top) counter value, and what type of waveform generation to be used, see table 46. modes of operation sup- ported by the timer/counter unit are: normal mode (counter), clear timer on compare match (ctc) mode, and three types of pu lse width modulation (pwm) modes. (see ?modes of operation? on page 93.). table 45. compare output mode, phase correct and phase and frequency correct pwm (1) com1a1/com1b1 com1a0/com1b0 description 0 0 normal port operation, oc1a/oc1b disconnected. 0 1 wgm13=0: normal port operation, oc1a/oc1b disconnected. wgm13=1: toggle oc1a on compare match, oc1b reserved. 1 0 clear oc1a/oc1b on compare match when up- counting. set oc1a/oc1b on compare match when downcounting. 1 1 set oc1a/oc1b on compare match when up- counting. clear oc1a/oc1b on compare match when downcounting.
105 attiny2313/v 2543f?avr?08/04 note: 1. the ctc1 and pwm11:0 bit definition names are obsolete . use the wgm12:0 definitions. however, the functionality and location of these bits are compatible with previous versions of the timer. table 46. waveform generation mode bit description (1) mode wgm13 wgm12 (ctc1) wgm11 (pwm11) wgm10 (pwm10) timer/counter mode of operation top update of ocr1 x at tov1 flag set on 0 0 0 0 0 normal 0xffff immediate max 1 0 0 0 1 pwm, phase correct, 8-bit 0x00ff top bottom 2 0 0 1 0 pwm, phase correct, 9-bit 0x01ff top bottom 3 0 0 1 1 pwm, phase correct, 10-bit 0x03ff top bottom 4 0 1 0 0 ctc ocr1a immediate max 5 0 1 0 1 fast pwm, 8-bit 0x00ff top top 6 0 1 1 0 fast pwm, 9-bit 0x01ff top top 7 0 1 1 1 fast pwm, 10-bit 0x03ff top top 8 1 0 0 0 pwm, phase and frequency correct icr1 bottom bottom 9 1 0 0 1 pwm, phase and frequency correct ocr1a bottom bottom 10 1 0 1 0 pwm, phase correct icr1 top bottom 11 1 0 1 1 pwm, phase correct ocr1a top bottom 12 1 1 0 0 ctc icr1 immediate max 13 1 1 0 1 (reserved) ? ? ? 14 1 1 1 0 fast pwm icr1 top top 15 1 1 1 1 fast pwm ocr1a top top
106 attiny2313/v 2543f?avr?08/04 timer/counter1 control register b ? tccr1b  bit 7 ? icnc1: input capture noise canceler setting this bit (to one) activates the input capture noise canceler. when the noise can- celer is activated, the input from the input capture pin (icp1) is filtered. the filter function requires four successive equal valued samples of the icp1 pin for changing its output. the input capture is therefore delaye d by four oscillator cycles when the noise canceler is enabled.  bit 6 ? ices1: input capture edge select this bit selects which edge on the input capture pin (icp1) that is used to trigger a cap- ture event. when the ices1 bit is written to zero, a falling (negative) edge is used as trigger, and when the ices1 bit is written to one, a rising (positive) edge will trigger the capture. when a capture is triggered according to t he ices1 setting, the counter value is copied into the input capture register (icr1). t he event will also set the input capture flag (icf1), and this can be used to cause an input capture interrupt, if this interrupt is enabled. when the icr1 is used as top value (see description of the wgm13:0 bits located in the tccr1a and the tccr1b register), t he icp1 is disconnected and consequently the input capture function is disabled.  bit 5 ? reserved bit this bit is reserved for future use. for ensuring compatibility with future devices, this bit must be written to zero when tccr1b is written.  bit 4:3 ? wgm13:2: waveform generation mode see tccr1a register description.  bit 2:0 ? cs12:0: clock select the three clock select bits select the clock source to be used by the timer/counter, see figure 48 and figure 49. if external pin modes are used for the timer/counter1, transitions on the t1 pin will clock the counter even if the pin is configured as an output. this feature allows software control of the counting. bit 7654 3210 icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 tccr1b read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 table 47. clock select bit description cs12 cs11 cs10 description 0 0 0 no clock source (timer/counter stopped). 001clk i/o /1 (no prescaling) 010clk i/o /8 (from prescaler) 011clk i/o /64 (from prescaler) 100clk i/o /256 (from prescaler) 101clk i/o /1024 (from prescaler) 1 1 0 external clock source on t1 pin. clock on falling edge. 1 1 1 external clock source on t1 pin. clock on rising edge.
107 attiny2313/v 2543f?avr?08/04 timer/counter1 control register c ? tccr1c  bit 7 ? foc1a: force output compare for channel a  bit 6 ? foc1b: force output compare for channel b the foc1a/foc1b bits are only active w hen the wgm13:0 bits specifies a non-pwm mode. however, for ensu ring compatibility with future devices, these bits must be set to zero when tccr1a is written when operating in a pwm mo de. when writing a logical one to the foc1a/foc1b bit, an immediate compare match is forced on the waveform generation unit. the oc1a/oc1b output is changed according to its com1x1:0 bits setting. note that the foc1a/foc1b bits are implemented as strobes. therefore it is the value present in the com1x1:0 bits that determine the effect of the forced compare. a foc1a/foc1b strobe will not ge nerate any interrup t nor will it clear the timer in clear timer on compare match (ctc) mode using ocr1a as top. the foc1a/foc1b bits are always read as zero. timer/counter1 ? tcnt1h and tcnt1l the two timer/counter i/o locations (tcnt1h and t cnt1l, combined tcnt1) give direct access, both for read and for write operations, to the timer/counter unit 16-bit counter. to ensure that both the high and low bytes are read and written simultaneously when the cpu accesses these registers, the access is performed using an 8-bit tempo- rary high byte register (temp). this temporar y register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 83. modifying the counter (tcnt1) while the counter is running introduces a risk of missing a compare match between tcnt1 and one of the ocr1x registers. writing to the tcnt1 register blocks (removes) the compare match on the following timer clock for all compare units. output compare register 1 a ? ocr1ah and ocr1al bit 7654 3210 foc1a foc1b ? ? ? ? ? ? tccr1c read/write w w r r r r r r initial value 0 0 0 0 0 0 0 0 bit 76543210 tcnt1[15:8] tcnt1h tcnt1[7:0] tcnt1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 ocr1a[15:8] ocr1ah ocr1a[7:0] ocr1al read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
108 attiny2313/v 2543f?avr?08/04 output compare register 1 b - ocr1bh and ocr1bl the output compare registers contain a 16- bit value that is continuously compared with the counter value (tcnt1). a match can be used to generate an output compare interrupt, or to generate a waveform output on the oc1x pin. the output compare registers are 16-bit in size. to ensure that both the high and low bytes are written simultaneously when the cpu writes to these registers, the access is performed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 83. input capture register 1 ? icr1h and icr1l the input capture is updated with the counter (tcnt1) value each time an event occurs on the icp1 pin (or optionally on the analog comparator output for timer/counter1). the input capture can be used for defining the counter top value. the input capture register is 16-bit in size. to ensure that both the high and low bytes are read simultaneously when the cpu accesses these registers, the access is per- formed using an 8-bit temporary high byte register (temp). this temporary register is shared by all the other 16-bit registers. see ?accessing 16-bit registers? on page 83. timer/counter interrupt mask register ? timsk  bit 7 ? toie1: timer/counter1, overflow interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts glo- bally enabled), the timer/counter1 overflow interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 43.) is executed when the tov1 flag, located in tifr, is set.  bit 6 ? ocie1a: timer/counter1, output compare a match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts glo- bally enabled), the timer/counter1 output compare a match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 43.) is executed when the ocf1a flag, located in tifr, is set.  bit 5 ? ocie1b: timer/counter1, output compare b match interrupt enable when this bit is written to one, and the i-flag in the status register is set (interrupts glo- bally enabled), the timer/counter1 output compare b match interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 43.) is executed when the ocf1b flag, located in tifr, is set.  bit 3 ? icie1: timer/counter1, input capture interrupt enable bit 76543210 ocr1b[15:8] ocr1bh ocr1b[7:0] ocr1bl read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 76543210 icr1[15:8] icr1h icr1[7:0] icr1l read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 bit 7 6 5 4 3 2 1 0 toie1 ocie1a ocie1b ?icie1 ocie0b toie0 ocie0a timsk read/write r/w r/w r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
109 attiny2313/v 2543f?avr?08/04 when this bit is written to one, and the i-flag in the status register is set (interrupts glo- bally enabled), the timer/counter1 input capture interrupt is enabled. the corresponding interrupt vector (see ?interrupts? on page 43.) is executed when the icf1 flag, located in tifr, is set. timer/counter interrupt flag register ? tifr  bit 7 ? tov1: timer/counter1, overflow flag the setting of this flag is dependent of the wgm13:0 bits setting. in normal and ctc modes, the tov1 flag is set when the timer overflows. refer to table 46 on page 105 for the tov1 flag behavior when using another wgm13:0 bit setting. tov1 is automatically cleared when the timer/counter1 overflow interrupt vector is executed. alternatively, tov1 can be cleared by writing a logic one to its bit location.  bit 6 ? ocf1a: timer/counter1, output compare a match flag this flag is set in the timer clock cycle a fter the counter (tcnt1) value matches the out- put compare register a (ocr1a). note that a forced output compare (f oc1a) strobe will not set the ocf1a flag. ocf1a is automatically cleared when the output compare match a interrupt vector is executed. alternatively, ocf1a can be cleared by writing a logic one to its bit location.  bit 5 ? ocf1b: timer/counter1, output compare b match flag this flag is set in the timer clock cycle a fter the counter (tcnt1) value matches the out- put compare register b (ocr1b). note that a forced output compare (f oc1b) strobe will not set the ocf1b flag. ocf1b is automatically cleared when the output compare match b interrupt vector is executed. alternatively, ocf1b can be cleared by writing a logic one to its bit location.  bit 3 ? icf1: timer/count er1, input capture flag this flag is set when a capture event occurs on the icp1 pin. when the input capture register (icr1) is set by the wgm13:0 to be used as the top value, the icf1 flag is set when the counter reaches the top value. icf1 is automatically cleared when the input capture interrupt vector is executed. alter- natively, icf1 can be cleared by writing a logic one to its bit location. bit 76543210 tov1 ocf1a ocf1b ? icf1 ocf0b tov0 ocf0a tifr read/write r/w r/w r/w r r/w r/w r/w r/w initial value00000000
110 attiny2313/v 2543f?avr?08/04 usart the universal synchronous and asynchronous serial receiver and transmitter (usart) is a highly flexible serial communication device. the main features are:  full duplex operation (i ndependent serial receive and transmit registers)  asynchronous or synchronous operation  master or slave clocked synchronous operation  high resolution baud rate generator  supports serial frames with 5, 6, 7, 8, or 9 data bits and 1 or 2 stop bits  odd or even parity generation and parity check supported by hardware  data overrun detection  framing error detection  noise filtering includes false start bit detection and digital low pass filter  three separate interrupts on tx complete , tx data register empty and rx complete  multi-processor communication mode  double speed asynchronous communication mode overview a simplified block diagram of the usart tran smitter is shown in figure 52. cpu acces- sible i/o registers and i/o pins are shown in bold. figure 52. usart block diagram (1) note: 1. refer to figure 1 on page 2, table 29 on page 56, and table 26 on page 54 for usart pin placement. parity generator ubrr[h:l] udr (transmit) ucsra ucsrb ucsrc baud rate generator transmit shift register receive shift register rxd txd pin control udr (receive) pin control xck data recovery clock recovery pin control tx control rx control parity checker data bus osc sync logic clock generator transmitter receiver
111 attiny2313/v 2543f?avr?08/04 the dashed boxes in the block diagram separate the three main parts of the usart (listed from the top): clock generator, transmitter and receiver. control registers are shared by all units. the clock generation l ogic consists of sync hronization logic for external clock input used by synchronous slave operation, and the baud rate generator. the xck (transfer clock) pin is only used by synchronous transfer mode. the trans- mitter consists of a single write buffer, a serial shift register, parity generator and control logic for handling different serial frame formats. the write buffer allows a contin- uous transfer of data without any delay between frames. the receiver is the most complex part of the usart module due to its clock and data recovery units. the recov- ery units are used for asynchronous data reception. in addition to the recovery units, the receiver includes a parity checker, control logic, a shift register and a two level receive buffer (udr). the receiver supports the same frame formats as the transmit- ter, and can detect frame error, data overrun and parity errors. avr usart vs. avr uart ? compatibility the usart is fully compatible with the avr uart regarding:  bit locations inside all usart registers.  baud rate generation.  transmitter operation.  transmit buffer functionality.  receiver operation. however, the receive buffering has two improvements that will affect the compatibility in some special cases:  a second buffer register has been added. the two buffer registers operate as a circular fifo buffer. therefore the udr must only be read once for each incoming data! more important is the fact that the error flags (fe and dor) and the ninth data bit (rxb8) are buffered with the data in the receive buffer. therefore the status bits must always be read before the udr register is read. otherwise the error status will be lost since the buffer state is lost.  the receiver shift register can now act as a third buffer level. this is done by allowing the received data to remain in the serial shift register (see figure 52) if the buffer registers are full, until a new start bit is detected. the usart is therefore more resistant to data overrun (dor) error conditions. the following control bits have changed name, but have same functionality and register location:  chr9 is changed to ucsz2.  or is changed to dor. clock generation the clock generation logic generates the bas e clock for the transmitter and receiver. the usart supports four modes of clock operation: normal asynchronous, double speed asynchronous, master synchronous and slave synchronous mode. the umsel bit in usart control and status regist er c (ucsrc) selects between asynchronous and synchronous operation. double speed (asynchronous mode only) is controlled by the u2x found in the ucsra register. when using synchronous mode (umsel = 1), the data direction register for the xck pin (ddr_xck) controls whether the clock source is internal (master mode) or external (slave mode). the xck pin is only active when using synchronous mode. figure 53 shows a block diagram of the clock generation logic.
112 attiny2313/v 2543f?avr?08/04 figure 53. clock generation logic, block diagram signal description: txclk transmitter clock (internal signal). rxclk receiver base clock (internal signal). xcki input from xck pin (internal signal). used for synchronous slave operation. xcko clock output to xck pin (internal signal). used for synchronous master operation. fosc xtal pin frequency (system clock). internal clock generation ? the baud rate generator internal clock generation is used for the asynchronous and the synchronous master modes of operation. the description in this section refers to figure 53. the usart baud rate register (ubrr) and the down-counter connected to it function as a programmable prescaler or baud rate generator. the down-counter, running at sys- tem clock (f osc ), is loaded with the ubrr value each time the counter has counted down to zero or when the ubrrl register is wr itten. a clock is generated each time the counter reaches zero. this clock is the baud rate generator clock output (= f osc /(ubrr+1)). the transmitter divides the baud rate generator clock output by 2, 8 or 16 depending on mode. the baud rate generator output is used directly by the receiver?s clock and data recovery units. however, the recovery units use a state machine that uses 2, 8 or 16 states depending on mode set by the state of the umsel, u2x and ddr_xck bits. table 48 contains equations for calculating the baud rate (in bits per second) and for calculating the ubrr value for each mode of operation using an internally generated clock source. prescaling down-counter /2 ubrr /4 /2 fosc ubrr+1 sync register osc xck pin txclk u2x umsel ddr_xck 0 1 0 1 xcki xcko ddr_xck rxcl k 0 1 1 0 edge detector ucpol
113 attiny2313/v 2543f?avr?08/04 note: 1. the baud rate is defined to be the transfer rate in bit per second (bps) baud baud rate (in bits per second, bps) f osc system oscillator clock frequency ubrr contents of the ubrrh and ubrrl registers, (0-4095) some examples of ubrr values for some system clock frequencies are found in table 56 (see page 133). double speed operation (u2x) the transfer rate can be doubled by setting t he u2x bit in ucsra. setting this bit only has effect for the asynchronous operation. set this bit to zero when using synchronous operation. setting this bit will reduce the divisor of the baud rate di vider from 16 to 8, effectively doubling the transfer rate for asynchronous communication. note however that the receiver will in this case only use half the number of samples (reduced from 16 to 8) for data sampling and clock recovery, and therefore a more accurate baud rate setting and system clock are required when this mode is used. for the transmitter, there are no downsides. external clock external clocking is used by the synchron ous slave modes of operation. the description in this section refers to figure 53 for details. external clock input from the xck pin is sa mpled by a synchronization register to mini- mize the chance of meta-stability. the output from the synchronization register must then pass through an edge detector before it can be used by the transmitter and receiver. this process introduces a two cp u clock period delay and therefore the max- imum external xck clock frequency is limited by the following equation: note that f osc depends on the stability of the system clock source. it is therefore recom- mended to add some margin to avoid possible loss of data due to frequency variations. table 48. equations for calculating baud rate register setting operating mode equation for calculating baud rate (1) equation for calculating ubrr value asynchronous normal mode (u2x = 0) asynchronous double speed mode (u2x = 1) synchronous master mode baud f osc 16 ubrr 1 + () -------------------------------------- - = ubrr f osc 16 baud ----------------------- - 1 ? = baud f osc 8 ubrr 1 + () ----------------------------------- = ubrr f osc 8 baud -------------------- 1 ? = baud f osc 2 ubrr 1 + () ----------------------------------- = ubrr f osc 2 baud -------------------- 1 ? = f xck f osc 4 ----------- <
114 attiny2313/v 2543f?avr?08/04 synchronous clock operation when synchronous mode is used (umsel = 1), the xck pin will be used as either clock input (slave) or clock output (master). the dependency between the clock edges and data sampling or data change is the same. t he basic principle is that data input (on rxd) is sampled at the opposite xck clock edge of the edge the data output (txd) is changed. figure 54. synchronous mode xck timing. the ucpol bit ucrsc selects which xck cloc k edge is used for data sampling and which is used for data change. as figure 54 shows, when ucpol is zero the data will be changed at rising xck edge and sampled at falling xck edge. if ucpol is set, the data will be changed at falling xck edge and sample d at rising xck edge. frame formats a serial frame is defined to be one character of data bits with synchronization bits (start and stop bits), and optionally a parity bit fo r error checking. the usart accepts all 30 combinations of the following as valid frame formats:  1 start bit  5, 6, 7, 8, or 9 data bits  no, even or odd parity bit  1 or 2 stop bits a frame starts with the start bit followed by the least significant data bit. then the next data bits, up to a total of nine, are succeeding, ending with the most significant bit. if enabled, the parity bit is inserted after the data bits, before the stop bits. when a com- plete frame is transmitted, it can be dire ctly followed by a new frame, or the communication line can be set to an idle (high) state. figure 55 illustrates the possible combinations of the frame formats. bits inside brackets are optional. figure 55. frame formats st start bit, always low. (n) data bits (0 to 8). p parity bit. can be odd or even. rxd / txd xck rxd / txd xck ucpol = 0 ucpol = 1 sample sample 1 0 2 3 4 [5] [6] [7] [8] [p] st sp1 [sp2] (st / idle) (idle) frame
115 attiny2313/v 2543f?avr?08/04 sp stop bit, always high. idle no transfers on the communication line (rxd or txd). an idle line must be high. the frame format used by th e usart is set by the ucsz2: 0, upm1:0 and usbs bits in ucsrb and ucsrc. the receiver and transmitter use the same setting. note that changing the setting of any of these bits will corrupt all ongoing communica tion for both the receiver and transmitter. the usart character size (ucsz2:0) bits select the number of data bits in the frame. the usart parity mode (upm1:0) bits enable and set the type of parity bit. the selec- tion between one or two stop bits is done by the usart stop bit select (usbs) bit. the receiver ignores the second stop bit. an fe (frame error) will therefore only be detected in the cases where the first stop bit is zero. parity bit calculation the parity bit is calculated by doing an exclus ive-or of all the data bits. if odd parity is used, the result of the exclusive or is inverted. the relation between the parity bit and data bits is as follows: p even parity bit using even parity p odd parity bit using odd parity d n data bit n of the character if used, the parity bit is located between the last data bit and first stop bit of a serial frame. usart initialization the usart has to be initialized before any communication can take place. the initial- ization process normally consists of setting the baud rate, setting frame format and enabling the transmitter or the receiver depending on the usage. for interrupt driven usart operation, the global interrupt flag should be cleared (and interrupts globally disabled) when doing the initialization. before doing a re-initialization with changed baud rate or frame format, be sure that there are no ongoing transmissions during th e period the registers are changed. the txc flag can be used to check that the transmitter has completed all transfers, and the rxc flag can be used to check that there are no unread data in the receive buffer. note that the txc flag must be cleared before each transmissi on (before udr is written) if it is used for this purpose. p even d n 1 ? d 3 d 2 d 1 d 0 0 p odd d n 1 ? d 3 d 2 d 1 d 0 1 = =
116 attiny2313/v 2543f?avr?08/04 the following simple usart initialization code examples show one assembly and one c function that are equal in functionality. the examples assume asynchronous opera- tion using polling (no interrupts enabled) and a fixed frame format. the baud rate is given as a function parameter. for the assembly code, the baud rate parameter is assumed to be stored in the r17:r16 registers. note: 1. the example code assumes that th e part specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?s bis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. more advanced initialization routines can be made that include frame format as parame- ters, disable interrupts and so on. however, many applications use a fixed setting of the baud and control registers, and for these types of applications the initialization code can be placed directly in the main routine, or be combined with initialization code for other i/o modules. assembly code example (1) usart_init: ; set baud rate out ubrrh, r17 out ubrrl, r16 ; enable receiver and transmitter ldi r16, (1<>8); ubrrl = ( unsigned char )baud; /* enable receiver and transmitter */ ucsrb = (1< 117 attiny2313/v 2543f?avr?08/04 data transmission ? the usart transmitter the usart transmitter is enabled by setting the transmit enable (txen) bit in the ucsrb register. when the transmitter is enabled, the normal port operation of the txd pin is overridden by the usart and given the function as the transmitter?s serial output. the baud rate, mode of operation and frame format must be set up once before doing any transmissions. if sy nchronous operation is used, the clock on the xck pin will be overridden and used as transmission clock. sending frames with 5 to 8 data bit a data transmission is initiated by loading the transmit buffer with the data to be trans- mitted. the cpu can load the transmit buffer by writing to the udr i/o location. the buffered data in the transmit buffer will be moved to the shift register when the shift register is ready to send a new frame. the shift register is loaded with new data if it is in idle state (no ongoing transmission) or immediately after the last stop bit of the previ- ous frame is transmitted. when the shift register is loaded with new data, it will transfer one complete frame at the rate given by the baud register, u2x bit or by xck depend- ing on mode of operation. the following code examples show a simple usart transmit func tion based on polling of the data register empty (udre) flag. when using frames with less than eight bits, the most significant bits written to the udr are ignored. the usart has to be initialized before the function can be used. for the assembly code, the data to be sent is assumed to be stored in register r16 note: 1. the example code assumes that th e part specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?s bis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. the function simply waits for the transmit buffer to be empty by checking the udre flag, before loading it with new data to be transmitted. if the data register empty interrupt is utilized, the interr upt routine writes the data into the buffer. assembly code example (1) usart_transmit: ; wait for empty transmit buffer sbis ucsra,udre rjmp usart_transmit ; put data (r16) into buffer, sends the data out udr,r16 ret c code example (1) void usart_transmit( unsigned char data ) { /* wait for empty transmit buffer */ while ( !( ucsra & (1< 118 attiny2313/v 2543f?avr?08/04 sending frames with 9 data bit if 9-bit characters are used (ucsz = 7), the ni nth bit must be written to the txb8 bit in ucsrb before the low byte of the characte r is written to udr. the following code examples show a transmit fu nction that handles 9-bit characters. for the assembly code, the data to be sent is assumed to be stored in registers r17:r16. notes: 1. these transmit functions are written to be general functions. they can be optimized if the contents of the ucsrb is static. for example, only the txb8 bit of the ucsrb register is used after initialization. 2. the example code assumes that the part specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?s bis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. the ninth bit can be used for indicating an address frame when using multi processor communication mode or for other protocol handling as for example synchronization. assembly code example (1)(2) usart_transmit: ; wait for empty transmit buffer sbis ucsra,udre rjmp usart_transmit ; copy 9th bit from r17 to txb8 cbi ucsrb,txb8 sbrc r17,0 sbi ucsrb,txb8 ; put lsb data (r16) into buffer, sends the data out udr,r16 ret c code example (1)(2) void usart_transmit( unsigned int data ) { /* wait for empty transmit buffer */ while ( !( ucsra & (1< 119 attiny2313/v 2543f?avr?08/04 transmitter flags and interrupts the usart transmitter has two flags that indicate its state: usart data register empty (udre) and transmit complete (txc). both flags can be used for generating interrupts. the data register empty (udre) flag indica tes whether the transmit buffer is ready to receive new data. this bit is set when the transmit buffer is empty, and cleared when the transmit buffer contains data to be transmitted that has not yet been moved into the shift register. for compatibility with fu ture devices, always write this bit to zero when writing the ucsra register. when the data register empty interrupt enable (udrie) bit in ucsrb is written to one, the usart data register empty interrupt will be executed as long as udre is set (pro- vided that global interrupt s are enabled). udre is cleared by writing udr. when interrupt-driven data transmission is used, the data register empty interrupt routine must either write new data to udr in order to clear udre or disable the data register empty interrupt, otherwise a new interrupt will occur once the interrupt routine terminates. the transmit complete (txc) flag bit is set one when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer. the txc flag bit is automati cally cleared when a transmit complete inter- rupt is executed, or it can be cleared by wr iting a one to its bit location. the txc flag is useful in half-duplex communication interf aces (like the rs-485 standard), where a transmitting application must enter receive mode and free the communication bus immediately after completing the transmission. when the transmit compete interrupt enable (txcie) bit in ucsrb is set, the usart transmit complete interrupt will be executed when the txc flag becomes set (provided that global interrupts are enabled). when the transmit complete interrupt is used, the interrupt handling routine does not have to clear the txc flag, this is done automatically when the interrupt is executed. parity generator the parity generator calculates the parity bit for the serial frame data. when parity bit is enabled (upm1 = 1), the transmitter control logic inserts the parity bit between the last data bit and the first stop bit of the frame that is sent. disabling the transmitter the disabling of the transmitter (setting the txen to zero) will not become effective until ongoing and pending transmissions are completed, i.e., when the transmit shift register and transmit buffer register do not contain data to be transmitted. when dis- abled, the transmitter will no longer override the txd pin.
120 attiny2313/v 2543f?avr?08/04 data reception ? the usart receiver the usart receiver is enabled by writing the receive enable (rxen) bit in the ucsrb register to one. when the receiver is enabled, the normal pin operation of the rxd pin is overridden by the usart and given the function as the receiver?s serial input. the baud rate, mode of operation and frame format must be set up once before any serial reception can be done. if synchronous operation is used, the clock on the xck pin will be used as transfer clock. receiving frames with 5 to 8 data bits the receiver starts data reception when it detects a valid start bit. each bit that follows the start bit will be sampled at the baud rate or xck clock, and shifted into the receive shift register until the first stop bit of a frame is received. a second stop bit will be ignored by the receiver. when the first stop bit is received, i.e., a complete serial frame is present in the receive shift register, the contents of the shift register will be moved into the receive buffer. the receive buffer can then be read by reading the udr i/o location. the following code example shows a simple usart receive function based on polling of the receive complete (rxc) flag. when using frames with less than eight bits the most significant bits of the data read fr om the udr will be masked to zero. the usart has to be initialized before the function can be used. note: 1. the example code assumes that the pa rt specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?s bis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. the function simply waits for data to be pres ent in the receive buffer by checking the rxc flag, before reading the buffer and returning the value. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsra, rxc rjmp usart_receive ; get and return received data from buffer in r16, udr ret c code example (1) unsigned char usart_receive( void ) { /* wait for data to be received */ while ( !(ucsra & (1< 121 attiny2313/v 2543f?avr?08/04 receiving frames with 9 data bits if 9-bit characters are used (ucsz=7) the ninth bit must be read from the rxb8 bit in ucsrb before reading the low bits from the udr. this rule applies to the fe, dor and upe status flags as well. read status fr om ucsra, then data from udr. reading the udr i/o location will change the state of the receive buffer fifo and consequently the txb8, fe, dor and upe bits, which all are stored in the fifo, will change. the following code example shows a simple u sart receive function that handles both nine bit characters and the status bits. assembly code example (1) usart_receive: ; wait for data to be received sbis ucsra, rxc rjmp usart_receive ; get status and 9th bit, then data from buffer in r18, ucsra in r17, ucsrb in r16, udr ; if error, return -1 andi r18,(1<> 1) & 0x01; return ((resh << 8) | resl); }
122 attiny2313/v 2543f?avr?08/04 note: 1. the example code assumes that the pa rt specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?s bis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. the receive function example reads all the i/o registers into the register file before any computation is done. this gives an opti mal receive buffer utilization since the buffer location read will be free to accept new data as early as possible. receive compete flag and interrupt the usart receiver has one flag that indicates the receiver state. the receive complete (rxc) flag indicates if there are unread data present in the receive buffer. this flag is one when unread data exist in the receive buffer, and zero when the receive buffer is empty (i.e., does not contain any unread data). if the receiver is disabled (rxen = 0), the receive buffer will be flushed and cons equently the rxc bit will become zero. when the receive complete interrupt enabl e (rxcie) in ucsrb is set, the usart receive complete interrupt will be executed as long as the rxc flag is set (provided that global interrupts are enabled). when interrupt-driven data reception is used, the receive complete routine must read the received data from udr in order to clear the rxc flag, otherwise a new interrupt will oc cur once the interrupt routine terminates. receiver error flags the usart receiver has three error flags: frame error (fe), data overrun (dor) and parity error (upe). all can be accessed by reading ucsra. common for the error flags is that they are located in the receive buffer together with the frame for which they indi- cate the error status. due to the buffering of the error flags, the ucsra must be read before the receive buffer (udr), since reading the udr i/o location changes the buffer read location. another equality for the error flags is that they can not be altered by soft- ware doing a write to the flag location. however, all flags must be set to zero when the ucsra is written for upward compatibilit y of future usart implementations. none of the error flags can generate interrupts. the frame error (fe) flag indicates the state of the first stop bit of the next readable frame stored in the receive buffer. the fe flag is zero when the stop bit was correctly read (as one), and the fe flag will be one when the stop bit was incorrect (zero). this flag can be used for detecting out-of-sync c onditions, detecting break conditions and protocol handling. the fe flag is not affected by the setting of the usbs bit in ucsrc since the receiver ignores all, except for th e first, stop bits. fo r compatibility with future devices, always set this bit to zero when writing to ucsra. the data overrun (dor) flag indicates data loss due to a receiver buffer full condition. a data overrun occurs when the receive buffer is full (two characters ), it is a new char- acter waiting in the receive shift register, and a new start bit is detected. if the dor flag is set there was one or more serial frame lost between the frame last read from udr, and the next frame read from udr. for compatibility with future devices, always write this bit to zero when writing to ucsra. the dor flag is cleared when the frame received was successfully moved from the shift register to the receive buffer. the parity error (upe) flag indicates that the next frame in the receive buffer had a par- ity error when receiv ed. if parity check is not enab led the upe bit will always be read zero. for compatibility with future devices, always set this bit to zero when writing to ucsra. for more details see ?parity bit calculation? on page 115 and ?parity checker? on page 123.
123 attiny2313/v 2543f?avr?08/04 parity checker the parity checker is active when the high usart parity mode (upm1) bit is set. type of parity check to be performed (odd or ev en) is selected by the upm0 bit. when enabled, the parity checker calculates the par ity of the data bits in incoming frames and compares the result with the parity bit from the serial frame. the result of the check is stored in the receive buffer together with the received data and stop bits. the parity error (upe) flag can then be read by software to check if the frame had a parity error. the upe bit is set if the next character that can be read from the receive buffer had a parity error when received and the parity checking was enabled at that point (upm1 = 1). this bit is valid until the receive buffer (udr) is read. disabling the receiver in contrast to the transmitter, disabling of the receiver will be immediate. data from ongoing receptions will therefore be lost. wh en disabled (i.e., the rxen is set to zero) the receiver will no longer override the normal function of the rxd port pin. the receiver buffer fifo will be flushed when the receiver is disabled. remaining data in the buffer will be lost flushing the receive buffer the receiver buffer fifo will be flushed when the receiver is disabled, i.e., the buffer will be emptied of its contents. unread data will be lost. if the buffer has to be flushed during normal operation, due to for instance an error condition, read the udr i/o loca- tion until the rxc flag is cleared. the follow ing code example shows how to flush the receive buffer. note: 1. the example code assumes that the pa rt specific header file is included. for i/o registers located in extended i/o map, ?in?, ?out?, ?s bis?, ?sbic?, ?cbi?, and ?sbi? instructions must be replaced with instructions that allow access to extended i/o. typically ?lds? and ?sts? combined with ?sbrs?, ?sbrc?, ?sbr?, and ?cbr?. asynchronous data reception the usart includes a clock recovery and a data recovery unit for handling asynchro- nous data reception. the clock recovery logi c is used for synchronizing the internally generated baud rate clock to the incoming asynchronous serial frames at the rxd pin. the data recovery logic samples and low pass filters each incoming bit, thereby improv- ing the noise immunity of the receiver. the asynchronous reception operational range depends on the accuracy of the internal baud rate clock, the rate of the incoming frames, and the frame size in number of bits. assembly code example (1) usart_flush: sbis ucsra, rxc ret in r16, udr rjmp usart_flush c code example (1) void usart_flush( void ) { unsigned char dummy; while ( ucsra & (1< 124 attiny2313/v 2543f?avr?08/04 asynchronous clock recovery the clock recovery logic synchronizes intern al clock to the incomi ng serial frames. fig- ure 56 illustrates the sampling pr ocess of the start bit of an incoming frame. the sample rate is 16 times the baud rate for normal mode, and eight times the baud rate for double speed mode. the horizontal arrows illustrate the synchronization variation due to the sampling process. note the larger time variation when using the double speed mode (u2x = 1) of operation. samples denoted zero are samples done when the rxd line is idle (i.e., no comm unication activity). figure 56. start bit sampling when the clock recovery logic detects a high (idle) to low (start) transition on the rxd line, the start bit detection sequence is initiated. let sample 1 denote the first zero-sam- ple as shown in the figure. the clock recovery logic then uses samples 8, 9, and 10 for normal mode, and samples 4, 5, and 6 for double speed mode (indicated with sample numbers inside boxes on the figure), to decide if a valid start bit is received. if two or more of these three samples have logical high levels (the majority wins), the start bit is rejected as a noise spike and the receiver starts looking for the next high to low-transi- tion. if however, a valid start bit is detected, the clock recovery logic is synchronized and the data recovery can begin. the synchronization process is repeated for each start bit. asynchronous data recovery when the receiver clock is synchronized to the start bit, the data recovery can begin. the data recovery unit uses a state machine that has 16 states for each bit in normal mode and eight states for each bit in double speed mode. figure 57 shows the sam- pling of the data bits and the parity bit. each of the samples is given a number that is equal to the state of the recovery unit. figure 57. sampling of data and parity bit the decision of the logic level of the received bit is taken by doing a majority voting of the logic value to the three samples in the center of the received bit. the center samples are emphasized on the figure by having the sample number inside boxes. the majority voting process is done as follows: if two or all three samples have high levels, the received bit is registered to be a logic 1. if two or all three samples have low levels, the received bit is registered to be a logic 0. this majority voting process acts as a low pass filter for the incoming signal on the rxd pin. the recovery process is then repeated until a complete frame is received. including the first stop bit. note that the receiver only uses the first stop bit of a frame. 1234567 8 9 10 11 12 13 14 15 16 12 start idle 0 0 bit 0 3 123 4 5 678 12 0 rxd sample (u2x = 0) sample (u2x = 1) 1234567 8 9 10 11 12 13 14 15 16 1 bit n 123 4 5 678 1 rxd sample (u2x = 0) sample (u2x = 1)
125 attiny2313/v 2543f?avr?08/04 figure 58 shows the sampling of the stop bit and the earliest possible beginning of the start bit of the next frame. figure 58. stop bit sampling and ne xt start bit sampling the same majority voting is done to the stop bit as done for the other bits in the frame. if the stop bit is registered to have a logic 0 value, the fram e error (fe) flag will be set. a new high to low transition indicating the start bit of a new frame can come right after the last of the bits used for majority voting. for normal speed mode, the first low level sample can be at point marked (a) in figur e 58. for double speed mode the first low level must be delayed to (b). (c) marks a stop bit of full length. the early start bit detec- tion influences the operational range of the receiver. asynchronous operational range the operational range of the receiver is dependent on the mismatch between the received bit rate and the internally generated baud rate. if the transmitter is sending frames at too fast or too slow bit rates, or the internally generated baud rate of the receiver does not have a similar (see tabl e 49) base frequency, the receiver will not be able to synchronize the frames to the start bit. the following equations can be used to calculate the ratio of the incoming data rate and internal receiver baud rate. d sum of character size and parity size (d = 5 to 10 bit) s samples per bit. s = 16 for normal speed mode and s = 8 for double speed mode. s f first sample number used for majority voting. s f = 8 for normal speed and s f = 4 for double speed mode. s m middle sample number used for majority voting. s m = 9 for normal speed and s m = 5 for double speed mode. r slow is the ratio of the slowest incoming data rate that can be accepted in relation to the receiver baud rate. r fast is the ratio of the fastest incoming data rate that can be accepted in relation to the receiver baud rate. table 49 and table 50 list the maximum receiver baud rate error that can be tolerated. note that normal speed mode has higher toleration of baud rate variations. 1234567 8 9 10 0/1 0/1 0/1 stop 1 123 4 5 6 0/1 rxd sample (u2x = 0) sample (u2x = 1) (a) (b) (c) r slow d 1 + () s s 1 ? ds ? s f ++ ------------------------------------------ - = r fast d 2 + () s d 1 + () ss m + ----------------------------------- =
126 attiny2313/v 2543f?avr?08/04 the recommendations of the maximum receiver baud rate error was made under the assumption that the receiver and transmitter equally divides the maximum total error. there are two possible sources for the receivers baud rate error. the receiver?s system clock (xtal) will always have some minor in stability over the supp ly voltage range and the temperature range. when using a crystal to generate the system clock, this is rarely a problem, but for a resonator the system clock may differ more than 2% depending of the resonators tolerance. the second source for the error is more controllable. the baud rate generator can not always do an exact division of the system frequency to get the baud rate wanted. in this case an ubrr value that gives an acceptable low error can be used if possible. table 49. recommended maximum receiver baud rate error for normal speed mode (u2x = 0) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 93.20 106.67 +6.67/-6.8 3.0 6 94.12 105.79 +5.79/-5.88 2.5 7 94.81 105.11 +5.11/-5.19 2.0 8 95.36 104.58 +4.58/-4.54 2.0 9 95.81 104.14 +4.14/-4.19 1.5 10 96.17 103.78 +3.78/-3.83 1.5 table 50. recommended maximum receiver baud rate error for double speed mode (u2x = 1) d # (data+parity bit) r slow (%) r fast (%) max total error (%) recommended max receiver error (%) 5 94.12 105.66 +5.66/-5.88 2.5 6 94.92 104.92 +4.92/-5.08 2.0 7 95.52 104,35 +4.35/-4.48 1.5 8 96.00 103.90 +3.90/-4.00 1.5 9 96.39 103.53 +3.53/-3.61 1.5 10 96.70 103.23 +3.23/-3.30 1.0
127 attiny2313/v 2543f?avr?08/04 multi-processor communication mode setting the multi-processor communication mode (mpcm) bit in ucsra enables a fil- tering function of incoming frames received by the usart receiver. frames that do not contain address information will be ignored and not put into the receive buffer. this effectively reduces the number of incomi ng frames that has to be handled by the cpu, in a system with multiple mcus that comm unicate via the same serial bus. the trans- mitter is unaffected by the mpcm setting, but has to be used differently when it is a part of a system utilizing the multi- processor communication mode. if the receiver is set up to receive frames that contain 5 to 8 data bits, then the first stop bit indicates if the frame contains data or address information. if the receiver is set up for frames with nine data bits, then the nint h bit (rxb8) is used for identifying address and data frames. when the frame type bit (the first stop or the ninth bit) is one, the frame contains an address. when the frame type bit is zero the frame is a data frame. the multi-processor communication mode enables several slave mcus to receive data from a master mcu. this is done by first decoding an address frame to find out which mcu has been addressed. if a particular slav e mcu has been addressed, it will receive the following data frames as normal, while the ot her slave mcus will ignore the received frames until another address frame is received. using mpcm for an mcu to act as a master mcu, it can use a 9-bit character frame format (ucsz = 7). the ninth bit (txb8) must be set when an address frame (txb8 = 1) or cleared when a data frame (txb = 0) is being transmitted. the slave mcus must in this case be set to use a 9-bit character frame format. the following procedure should be used to exchange data in multi-processor communi- cation mode: 1. all slave mcus are in multi-processo r communication mode (mpcm in ucsra is set). 2. the master mcu sends an address frame, and all slaves receive and read this frame. in the slave mcus, the rxc flag in ucsra will be set as normal. 3. each slave mcu reads the udr register and determines if it has been selected. if so, it clears the mpcm bit in ucsra, otherwise it waits for the next address byte and keeps the mpcm setting. 4. the addressed mcu will receive all data frames until a new address frame is received. the other slave mcus, which still have the mpcm bit set, will ignore the data frames. 5. when the last data frame is received by the addressed mcu, the addressed mcu sets the mpcm bit and waits for a new address frame from master. the process then repeats from 2. using any of the 5- to 8-bit character frame formats is possible, but impractical since the receiver must change between using n and n+1 character frame formats. this makes full-duplex operation difficult since the transmitter and receiver uses the same charac- ter size setting. if 5- to 8-bit character frames are used, the transmitter must be set to use two stop bit (usbs = 1) since the first stop bit is used for indicating the frame type. do not use read-modify-write instructions (s bi and cbi) to set or clear the mpcm bit. the mpcm bit shares the same i/o location as the txc flag and this might accidentally be cleared when using sbi or cbi instructions.
128 attiny2313/v 2543f?avr?08/04 usart register description usart i/o data register ? udr the usart transmit data buffer register and usart receive data buffer registers share the same i/o address re ferred to as usart data re gister or udr. the transmit data buffer register (txb) will be the de stination for data wri tten to the udr register location. reading the udr regi ster location will return the contents of the receive data buffer register (rxb). for 5-, 6-, or 7-bit characters the upper unus ed bits will be ignored by the transmitter and set to zero by the receiver. the transmit buffer can only be written wh en the udre flag in the ucsra register is set. data written to udr when the udre flag is not set, will be ignored by the usart transmitter. when data is written to the transmit buffer, and the transmitter is enabled, the transmitter will load the data into the tran smit shift register when the shift register is empty. then the data will be se rially transmitted on the txd pin. the receive buffer consists of a two level fifo. the fifo will change its state whenever the receive buffer is accessed. due to this behavior of the receive buffer, do not use read-modify-write instructions (sbi and cbi) on this location. be careful when using bit test instructions (sbic and sbis), since these also will ch ange the state of the fifo. usart control and status register a ? ucsra  bit 7 ? rxc: usart receive complete this flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). if the receiver is dis- abled, the receive buffer will be flushed and consequently th e rxc bit will become zero. the rxc flag can be used to generate a receive complete interrupt (see description of the rxcie bit).  bit 6 ? txc: usart transmit complete this flag bit is set when the entire frame in the transmit shift register has been shifted out and there are no new data currently present in the transmit buffer (udr). the txc flag bit is automatically cleared when a transmit complete interrupt is executed, or it can be cleared by writing a one to its bit location. the txc flag can generate a transmit complete interrupt (see description of the txcie bit). bit 7 6 5 4 3 2 1 0 rxb[7:0] udr (read) txb[7:0] udr (write) read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0 bit 76543210 rxc txc udre fe dor upe u2x mpcm ucsra read/write r r/w r r r r r/w r/w initial value00100000
129 attiny2313/v 2543f?avr?08/04  bit 5 ? udre: usart data register empty the udre flag indicates if the transmit buffe r (udr) is ready to receive new data. if udre is one, the buffer is empty, and therefore ready to be written. the udre flag can generate a data register empty interrupt (see description of the udrie bit). udre is set after a reset to indicate that the transmitter is ready.  bit 4 ? fe: frame error this bit is set if the next character in the receive buffer had a frame error when received. i.e., when the first stop bit of the next character in the receive buffer is zero. this bit is valid until the receive buffer (udr ) is read. the fe bit is zero when the stop bit of received data is one. always set th is bit to zero when writing to ucsra.  bit 3 ? dor: data overrun this bit is set if a data overrun condition is detected. a data overrun occurs when the receive buffer is full (two char acters), it is a new characte r waiting in the receive shift register, and a new start bit is detected. this bit is valid until the receive buffer (udr) is read. always set this bit to zero when writing to ucsra.  bit 2 ? upe: usart parity error this bit is set if the next character in the receive buffer had a parity error when received and the parity checking was enabled at that point (upm1 = 1). this bit is valid until the receive buffer (udr) is read. always set this bit to zero when writing to ucsra.  bit 1 ? u2x: double the usart transmission speed this bit only has effect for the asynchronous operation. write this bit to zero when using synchronous operation. writing this bit to one will reduce the divisor of the baud rate divider from 16 to 8 effec- tively doubling the transfer rate for asynchronous communication.  bit 0 ? mpcm: multi-processor communication mode this bit enables the multi-processor communication mode. when the mpcm bit is writ- ten to one, all the incoming frames received by the usart receiver that do not contain address information will be igno red. the transmitter is una ffected by the mpcm setting. for more detailed information see ?multi-processor communication mode? on page 127.
130 attiny2313/v 2543f?avr?08/04 usart control and status register b ? ucsrb  bit 7 ? rxcie: rx complete interrupt enable writing this bit to one enables interrupt on the rxc flag. a usart receive complete interrupt will be generat ed only if the rxcie bit is writ ten to one, t he global interrupt flag in sreg is written to one and the rxc bit in ucsra is set.  bit 6 ? txcie: tx complete interrupt enable writing this bit to one enables interrupt on the txc flag. a usart transmit complete interrupt will be generated only if the txcie bi t is written to one, the global interrupt flag in sreg is written to one and the txc bit in ucsra is set.  bit 5 ? udrie: usart data register empty interrupt enable writing this bit to one enables interrupt on the udre flag. a data register empty inter- rupt will be generated only if the udrie bit is written to one, the global interrupt flag in sreg is written to one and the udre bit in ucsra is set.  bit 4 ? rxen: receiver enable writing this bit to one enables the usart receiver. the receiver will override normal port operation for the rxd pin when enabled. disabling the receiver will flush the receive buffer invalidating the fe, dor, and upe flags.  bit 3 ? txen: transmitter enable writing this bit to one enables the usart transmitter. the trans mitter will override nor- mal port operation for the txd pin when enabled. the disabling of the transmitter (writing txen to zero) will not become effe ctive until ongoing and pending transmis- sions are completed, i.e., when the transmit shift register and transmit buffer register do not contain data to be tr ansmitted. when disabled, the transmitte r will no longer override the txd port.  bit 2 ? ucsz2: character size the ucsz2 bits combined with the ucsz1:0 bi t in ucsrc sets the number of data bits (character size) in a frame the receiver and transmitter use.  bit 1 ? rxb8: receive data bit 8 rxb8 is the ninth data bit of the received character when operating with serial frames with nine data bits. must be read before reading the low bits from udr.  bit 0 ? txb8: transmit data bit 8 txb8 is the ninth data bit in the character to be transmitted when operating with serial frames with nine data bits. must be written before writing the low bits to udr. bit 76543210 rxcie txcie udrie rxen txen ucsz2 rxb8 txb8 ucsrb read/write r/w r/w r/w r/w r/w r/w r r/w initial value00000000
131 attiny2313/v 2543f?avr?08/04 usart control and status register c ? ucsrc  bit 6 ? umsel: usart mode select this bit selects between asynchronous and synchronous mode of operation.  bit 5:4 ? upm1:0: parity mode these bits enable and set type of parity generation and check. if enabled, the transmit- ter will automatically generate and send th e parity of the transmitted data bits within each frame. the receiver will generate a parity value for the incoming data and com- pare it to the upm0 setting . if a mismatch is detected, the upe fl ag in ucsra will be set.  bit 3 ? usbs: stop bit select this bit selects the number of stop bits to be inserted by the transmitter. the receiver ignores this setting.  bit 2:1 ? ucsz1:0: character size the ucsz1:0 bits combined with the ucsz2 bit in ucsrb sets the number of data bits (character size) in a frame the receiver and transmitter use. see table 54 on page 132. bit 76543210 ? umsel upm1 upm0 usbs ucsz1 ucsz0 ucpol ucsrc read/write r r/w r/w r/w r/w r/w r/w r/w initial value00000110 table 51. umsel bit settings umsel mode 0 asynchronous operation 1 synchronous operation table 52. upm bits settings upm1 upm0 parity mode 0 0 disabled 01reserved 1 0 enabled, even parity 1 1 enabled, odd parity table 53. usbs bit settings usbs stop bit(s) 01-bit 12-bit
132 attiny2313/v 2543f?avr?08/04  bit 0 ? ucpol: clock polarity this bit is used for synchronous mode only. write this bit to zero when asynchronous mode is used. the ucpol bit sets th e relationship between data output change and data input sample, and th e synchronous clock (xck). usart baud rate registers ? ubrrl and ubrrh  bit 15:12 ? reserved bits these bits are reserved for future use. fo r compatibility with future devices, these bit must be written to zero when ubrrh is written.  bit 11:0 ? ubrr11:0: usart baud rate register this is a 12-bit register which contains the usart baud rate. the ubrrh contains the four most significant bits, and the ubrrl contai ns the eight least significant bits of the usart baud rate. ongoing transmissions by the transmitter and receiver will be cor- rupted if the baud rate is changed. writing ubrrl will tr igger an imme diate update of the baud rate prescaler. table 54. ucsz bits settings ucsz2 ucsz1 ucsz0 character size 0005-bit 0016-bit 0107-bit 0118-bit 100reserved 101reserved 110reserved 1119-bit table 55. ucpol bit settings ucpol transmitted data changed (output of txd pin) received data sampled (input on rxd pin) 0 rising xck edge falling xck edge 1 falling xck edge rising xck edge bit 151413121110 9 8 ???? ubrr[11:8] ubrrh ubrr[7:0] ubrrl 76543210 read/write r r r r r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000 00000000
133 attiny2313/v 2543f?avr?08/04 examples of baud rate setting for standard crystal and resonator frequencies, the most commonly used baud rates for asynchronous operation can be generated by using the ubrr settings in table 56. ubrr values which yield an actual baud rate differing less than 0.5% from the target baud rate, are bold in the ta ble. higher error ratings are a cceptable, but the receiver will have less noise resistance when the error rati ngs are high, especially for large serial frames (see ?asynchronous operational range? on page 125). the error values are cal- culated using the following equation: error[%] baudrate closest match baudrate -------------------------------------------------------- 1 ? ?? ?? 100% ? = table 56. examples of ubrr settings for co mmonly used oscillator frequencies baud rate (bps) f osc = 1.0000 mhz f osc = 1.8432 mhz f osc = 2.0000 mhz u2x = 0 u2x = 1 u2x = 0 u2x = 1 u2x = 0 u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 250.2%510.2%470.0%950.0%510.2%1030.2% 4800 120.2%250.2%230.0%470.0%250.2%510.2% 9600 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 12 0.2% 25 0.2% 14.4k 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 19.2k 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 28.8k 1 8.5% 3 8.5% 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 38.4k 1 -18.6% 2 8.5% 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 57.6k 0 8.5% 1 8.5% 1 0.0% 3 0.0% 1 8.5% 3 8.5% 76.8k ? ? 1 -18.6% 1 -25.0% 2 0.0% 1 -18.6% 2 8.5% 115.2k ? ? 0 8.5% 0 0.0% 1 0.0% 0 8.5% 1 8.5% 230.4k??????00.0%???? 250k??????????00.0% max. (1) 62.5 kbps 125 kbps 115.2 kbps 2 30.4 kbps 125 kbps 250 kbps 1. ubrr = 0, error = 0.0%
134 attiny2313/v 2543f?avr?08/04 table 57. examples of ubrr settings for commonl y used oscillator frequencies (continued) baud rate (bps) f osc = 3.6864 mhz f osc = 4.0000 mhz f osc = 7.3728 mhz u2x = 0u2x = 1u2x = 0u2x = 1u2x = 0u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 95 0.0% 191 0.0% 103 0.2% 207 0.2% 191 0.0% 383 0.0% 4800 47 0.0% 95 0.0% 51 0.2% 103 0.2% 95 0.0% 191 0.0% 9600 230.0%470.0%250.2%510.2%470.0%950.0% 14.4k 15 0.0% 31 0.0% 16 2.1% 34 -0.8% 31 0.0% 63 0.0% 19.2k 11 0.0% 23 0.0% 12 0.2% 25 0.2% 23 0.0% 47 0.0% 28.8k 7 0.0% 15 0.0% 8 -3.5% 16 2.1% 15 0.0% 31 0.0% 38.4k 5 0.0% 11 0.0% 6 -7.0% 12 0.2% 11 0.0% 23 0.0% 57.6k 3 0.0% 7 0.0% 3 8.5% 8 -3.5% 7 0.0% 15 0.0% 76.8k 2 0.0% 5 0.0% 2 8.5% 6 -7.0% 5 0.0% 11 0.0% 115.2k 1 0.0% 3 0.0% 1 8.5% 3 8.5% 3 0.0% 7 0.0% 230.4k 0 0.0% 1 0.0% 0 8.5% 1 8.5% 1 0.0% 3 0.0% 250k 0 -7.8% 1 -7.8% 0 0.0% 1 0.0% 1 -7.8% 3 -7.8% 0.5m ? ? 0 -7.8% ? ? 0 0.0% 0 -7.8% 1 -7.8% 1m ??????????0-7.8% max. (1) 230.4 kbps 460.8 kbps 250 kbps 0.5 mbps 460.8 kbps 921.6 kbps 1. ubrr = 0, error = 0.0%
135 attiny2313/v 2543f?avr?08/04 table 58. examples of ubrr settings for commonl y used oscillator frequencies (continued) baud rate (bps) f osc = 8.0000 mhz f osc = 11.0592 mhz f osc = 14.7456 mhz u2x = 0 u2x = 1 u2x = 0 u2x = 1 u2x = 0 u2x = 1 ubrr error ubrr error ubrr error ubrr error ubrr error ubrr error 2400 207 0.2% 416 -0.1% 287 0.0% 575 0.0% 383 0.0% 767 0.0% 4800 103 0.2% 207 0.2% 143 0.0% 287 0.0% 191 0.0% 383 0.0% 9600 51 0.2% 103 0.2% 71 0.0% 143 0.0% 95 0.0% 191 0.0% 14.4k 34 -0.8% 68 0.6% 47 0.0% 95 0.0% 63 0.0% 127 0.0% 19.2k 25 0.2% 51 0.2% 35 0.0% 71 0.0% 47 0.0% 95 0.0% 28.8k 16 2.1% 34 -0.8% 23 0.0% 47 0.0% 31 0.0% 63 0.0% 38.4k 12 0.2% 25 0.2% 17 0.0% 35 0.0% 23 0.0% 47 0.0% 57.6k 8 -3.5% 16 2.1% 11 0.0% 23 0.0% 15 0.0% 31 0.0% 76.8k 6 -7.0% 12 0.2% 8 0.0% 17 0.0% 11 0.0% 23 0.0% 115.2k 3 8.5% 8 -3.5% 5 0.0% 11 0.0% 7 0.0% 15 0.0% 230.4k 1 8.5% 3 8.5% 2 0.0% 5 0.0% 3 0.0% 7 0.0% 250k 1 0.0% 3 0.0% 2 -7.8% 5 -7.8% 3 -7.8% 6 5.3% 0.5m 0 0.0% 1 0.0% ? ? 2 -7.8% 1 -7.8% 3 -7.8% 1m ? ? 0 0.0% ? ? ? ? 0 -7.8% 1 -7.8% max. (1) 0.5 mbps 1 mbps 691.2 kbps 1.3824 mbps 921.6 kbps 1.8432 mbps 1. ubrr = 0, error = 0.0%
136 attiny2313/v 2543f?avr?08/04 table 59. examples of ubrr settings for commonly used oscillator frequencies (continued) baud rate (bps) f osc = 16.0000 mhz u2x = 0 u2x = 1 ubrr error ubrr error 2400 416 -0.1% 832 0.0% 4800 207 0.2% 416 -0.1% 9600 103 0.2% 207 0.2% 14.4k 68 0.6% 138 -0.1% 19.2k 51 0.2% 103 0.2% 28.8k 34 -0.8% 68 0.6% 38.4k 25 0.2% 51 0.2% 57.6k 16 2.1% 34 -0.8% 76.8k 12 0.2% 25 0.2% 115.2k 8 -3.5% 16 2.1% 230.4k 3 8.5% 8 -3.5% 250k 3 0.0% 7 0.0% 0.5m 1 0.0% 3 0.0% 1m 0 0.0% 1 0.0% max. (1) 1. ubrr = 0, error = 0.0% 1 mbps 2 mbps
137 attiny2313/v 2543f?avr?08/04 universal serial interface ? usi the universal serial interface, or usi, provides the basic hardware resources needed for serial communication. combined with a minimum of control software, the usi allows significantly higher transfer rates and uses less code space than solutions based on software only. interrupts are included to minimize the processor load. the main features of the usi are:  two-wire synchronous data tr ansfer (master or slave, f sclmax = f ck /16)  three-wire synchronous data transfer (master, f sckmax = f ck /2, slave f sckmax = f ck /4)  data received interrupt  wake-up from idle mode  in two-wire mode: wake-up from all sl eep modes, including power-down mode  two-wire start condition detector with interrupt capability overview a simplified block diagram of the usi is show n on figure 59. for the actual placement of i/o pins, refer to ?pinout attiny2313? on pag e 2. cpu accessible i/o registers, includ- ing i/o bits and i/o pins, are shown in bold. the device-specific i/o register and bit locations are listed in the ?usi register descriptions? on page 143. figure 59. universal serial inte rface, block diagram the 8-bit shift register is directly accessi ble via the data bus and contains the incoming and outgoing data. the register has no buffering so the data must be read as quickly as possible to ensure that no data is lost. the mo st significant bit is connected to one of two output pins depending of the wire mode config uration. a transparent latch is inserted between the serial register output and output pin, which delays the change of data out- put to the opposite clock edge of the data input sampling. the serial input is always sampled from the data input (di) pin independent of the configuration. the 4-bit counter can be both read and written via the data bus, and can generate an overflow interrupt. both the serial regi ster and the counter are clocked simultaneously by the same clock source. this allows the counter to count the number of bits received or transmitted and generate an interrupt when the transfer is complete. note that when an external clock source is selected the c ounter counts both clock edges. in this case the counter counts the number of edges, and not the number of bits. the clock can be selected from three different sources: the usck pin, timer0 overflow, or from software. data bus usipf usitc usiclk usics0 usics1 usioif usioie usidc usisif usiwm0 usiwm1 usisie bit7 two-wire clock control unit do (output only) di/sda (input/open drain) usck/scl (input/open drain) 4-bit counter usidr usisr dq le usicr clock hold tim0 comp bit0 [1] 3 0 1 2 3 0 1 2 0 1 2
138 attiny2313/v 2543f?avr?08/04 the two-wire clock control unit can generate an interrupt when a start condition is detected on the two-wire bus. it can also gener ate wait states by holding the clock pin low after a start condition is detected, or after the counter overflows. functional descriptions three-wire mode the usi three-wire mode is compliant to the serial peripheral interface (spi) mode 0 and 1, but does not have the slave select (ss) pin functionality. however, this feature can be implemented in software if necessary. pin names used by this mode are: di, do, and usck. figure 60. three-wire mode operation, simplified diagram figure 60 shows two usi units operating in three-wire mode, one as master and one as slave. the two shift registers are interconnected in such way that after eight usck clocks, the data in each register are interchanged. the same clock also increments the usi?s 4-bit counter. the counter overflow (interrupt) flag, or usioif, can therefore be used to determine when a transfer is completed. the clock is generated by the master device software by toggling the usck pin via the port register or by writing a one to the usitc bit in usicr. figure 61. three-wire mode, timing diagram slave master bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 do di usck bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 do di usck portxn msb msb 654321lsb 1 2 3 4 5 6 7 8 654321lsb usck usck do di d c b a e cycle ( reference )
139 attiny2313/v 2543f?avr?08/04 the three-wire mode timing is shown in figure 61. at the top of the figure is a usck cycle reference. one bit is shifted into the usi shift register (usidr) for each of these cycles. the usck timing is shown for both external clock modes. in external clock mode 0 (usics0 = 0), di is sampled at positive edges, and do is changed (data regis- ter is shifted by one) at negative edges. external clock mode 1 (usics0 = 1) uses the opposite edges versus mode 0, i.e., samples data at negative and changes the output at positive edges. the usi clock modes corresponds to the spi data mode 0 and 1. referring to the timing diagram (figure 61.), a bus transfer involves the following steps: 1. the slave device and master device sets up its data output and, depending on the protocol used, enables its output driver (mark a and b). the output is set up by writing the data to be transmitted to the serial data register. enabling of the output is done by setting the corresponding bit in the port data direction regis- ter. note that point a and b does not have any specific order, but both must be at least one half usck cycle before point c where the data is sampled. this must be done to ensure that the data setup requirement is satisfied. the 4-bit counter is reset to zero. 2. the master generates a clock pulse by software toggling the usck line twice (c and d). the bit value on the slave and master?s data input (di) pin is sampled by the usi on the first edge (c), and the data output is changed on the opposite edge (d). the 4-bit counter will count both edges. 3. step 2. is repeated eight times for a complete register (byte) transfer. 4. after eight clock pulses (i .e., 16 clock edges) the coun ter will overflow and indi- cate that the transfer is completed. the data bytes transferred must now be processed before a new transfer can be in itiated. the overflow interrupt will wake up the processor if it is set to idle mode. depending of the protocol used the slave device can now set its output to high impedance. spi master operation example the following code demonstrates how to use the usi module as a spi master: spitransfer: out usidr,r16 ldi r16,(1< 140 attiny2313/v 2543f?avr?08/04 the following code demonstrates how to use the usi module as a spi master with max- imum speed (fsck = fck/2): spitransfer_fast: out usidr,r16 ldi r16,(1< 141 attiny2313/v 2543f?avr?08/04 ferred to the master device, and when the transfer is completed the data received from the master is stored back into the r16 register. note that the first two instructions is for initialization only and needs only to be executed once.these instructions sets three-wire mode and positive edge shift register clock. the loop is repeated until the usi counter overflow flag is set. two-wire mode the usi two-wire mode does not incorporate slew rate limiting on outputs and input noise filtering. pin names used by this mode are scl and sda. figure 62. two-wire mode operation, simplified diagram figure 62 shows two usi units operating in two-wire mode, one as master and one as slave. it is only the physical layer that is shown since the system operation is highly dependent of the communication scheme used. the main differences between the mas- ter and slave operation at this level, is the serial clock generation which is always done by the master, and only the slave uses the clock control unit. clock generation must be implemented in software, but the shift operation is done automatically by both devices. note that only clocking on negative edge for shi fting data is of practical use in this mode. the slave can insert wait states at start or end of transfer by forcing the scl clock low. this means that the master must always ch eck if the scl line was actually released after it has generated a positive edge. since the clock also increments the counter, a counter overflow can be used to indicate that the transfer is completed. the clock is generated by the master by toggling the usck pin via the port register. the data direction is not given by the physical layer. a protocol, like the one used by the twi-bus, must be implemented to control the data flow. master slave bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 sda scl bit7 bit6 bit5 bit4 bit3 bit2 bit1 bit0 two-wire clock control unit hold scl portxn sda scl vcc
142 attiny2313/v 2543f?avr?08/04 figure 63. two-wire mode, typical timing diagram referring to the timing diagram (figure 63.), a bus transfer involves the following steps: 1. the a start condition is generated by th e master by forcing the sda low line while the scl line is high (a). sda can be forced low either by writing a zero to bit 7 of the shift register, or by setting the corresponding bit in the port register to zero. note that the data direction register bit must be set to one for the output to be enabled. the slave device?s start detector logic (figure 64.) detects the start condition and sets the usisif flag. the flag can generate an interrupt if necessary. 2. in addition, the start detector will hold the scl line low after the master has forced an negative edge on this line (b). this allows the slave to wake up from sleep or complete its other tasks before setting up the shift register to receive the address. this is done by clearing the start condition flag and reset the counter. 3. the master set the first bit to be transferred and releases the scl line (c). the slave samples the data and shift it into the serial register at the positive edge of the scl clock. 4. after eight bits are transferred containing slave address and data direction (read or write), the slave counter overflows and the scl line is forced low (d). if the slave is not the one the master has addressed, it releases the scl line and waits for a new start condition. 5. if the slave is addressed it holds the sda line low during the acknowledgment cycle before holding the scl line low again (i.e., the counter register must be set to 14 before releasing scl at (d)). depending of the r/w bit the master or slave enables its output. if the bit is set, a master read operation is in progress (i.e., the slave drives the sda line) the slave can hold the scl line low after the acknowledge (e). 6. multiple bytes can now be transmitted, a ll in same direction, until a stop condition is given by the master (f). or a new start condition is given. if the slave is not able to receive more data it does not acknowledge the data byte it has last received. when the master does a read operation it must terminate the operation by force the acknowledge bit low after the last byte transmitted. figure 64. start condition detector, logic diagram p s address 1 - 7 8 9 r/w ack ack 1 - 8 9 data ack 1 - 8 9 data sda scl a b d e c f sda scl write( usisif) clock hold usisif dq clr dq clr
143 attiny2313/v 2543f?avr?08/04 start condition detector the start condition detector is shown in figure 64. the sda line is delayed (in the range of 50 to 300 ns) to ensure valid sampling of the scl line. the start condition detector is working asynchronously and can therefore wake up the processor from the power-down sleep mode. however, the protocol used might have restrictions on the scl hold time. therefore, when using this feature in this case the oscillator start-up time set by the cksel fuses (see ?clock systems and their distribu- tion? on page 21) must also be taken into the consideration. alternative usi usage when the usi unit is not used for serial communication, it can be set up to do alternative tasks due to its flexible design. half-duplex asynchronous data transfer by utilizing the shift register in three-wire mode, it is possible to implement a more compact and higher performance uart than by software only. 4-bit counter the 4-bit counter can be used as a stand-alone counter with overflow interrupt. note that if the counter is clocked externally , both clock edges will generate an increment. 12-bit timer/counter combining the usi 4-bit counter and timer/counter0 allows them to be used as a 12-bit counter. edge triggered external interrupt by setting the counter to maximum value (f ) it can function as an additional external interrupt. the overflow flag and interrupt ena ble bit are then used for the external inter- rupt. this feature is selected by the usics1 bit. software interrupt the counter overflow interrupt can be used as a software interrupt triggered by a clock strobe. usi register descriptions usi data register ? usidr the usi uses no buffering of the serial regi ster, i.e., when accessing the data register (usidr) the serial register is accessed direct ly. if a serial clock occurs at the same cycle the register is written, the re gister will contain the value writ ten and no shift is performed. a (left) shift operation is performed depending of the usics1..0 bits setting. the shift operation can be controlled by an external clock edge, by a timer/counter0 overflow, or directly by software using the usiclk str obe bit. note that even when no wire mode is selected (usiwm1..0 = 0) both the external data input (di/sda) and the external clock input (usck/scl) can still be us ed by the shift register. the output pin in use, do or sda depending on the wire mode, is connected via the out- put latch to the most significant bit (bit 7) of the data register. the output latch is open (transparent) during the first half of a serial clock cycle when an external clock source is selected (usics1 = 1), and constantly open when an internal cl ock source is used (usics1 = 0). the output will be changed imme diately when a new msb written as long as the latch is open. the latch ensures t hat data input is sampled and data output is changed on opposite clock edges. bit 7 6 5 4 3 2 1 0 msb lsb usidr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
144 attiny2313/v 2543f?avr?08/04 note that the corresponding data direction register to the pin must be set to one for enabling data output from the shift register. usi status register ? usisr the status register contains interrupt flags, line status flags and the counter value.  bit 7 ? usisif: start condition interrupt flag when two-wire mode is selected, the usisif flag is set (to one) when a start condition is detected. when output disable mode or three-wire mode is selected and (usicsx = 0b11 & usiclk = 0) or (usics = 0b10 & usiclk = 0), any edge on the sck pin sets the flag. an interrupt will be generated wh en the flag is set while the usisie bit in usicr and the global interrupt enable flag are set. the fl ag will only be cleared by writing a logical one to the usisif bit. clearing this bit will re lease the start detection hold of uscl in two- wire mode. a start condition interrup t will wake-up the processo r from all sleep modes.  bit 6 ? usioif: counter overflow interrupt flag this flag is set (one) when the 4-bit counter overflows (i.e., at the transition from 15 to 0). an interrupt will be generated when the flag is set while the usioie bit in usicr and the global interrupt enable fl ag are set. the flag will only be cleared if a one is written to the usioif bit. clearing this bit will releas e the counter overflow hold of scl in two- wire mode. a counter overflow interrupt will wake-up the processor from idle sleep mode.  bit 5 ? usipf: stop condition flag when two-wire mode is selected, the usipf flag is set (one) when a stop condition is detected. the flag is cleared by writing a one to this bit. note that this is not an interrupt flag. this signal is useful when implem enting two-wire bus master arbitration.  bit 4 ? usidc: data output collision this bit is logical one when bit 7 in the shift register differs from the physical pin value. the flag is only valid when two-wire mode is used. this signal is useful when imple- menting two-wire bus master arbitration.  bits 3..0 ? usicnt3..0: counter value these bits reflect the current 4-bit counter va lue. the 4-bit counter value can directly be read or written by the cpu. the 4-bit counter increments by one for each clock generated either by the external clock edge detector, by a timer/counter0 ov erflow, or by software using usiclk or usitc strobe bits. the clock source depends of the setting of the usics1..0 bits. for external clock operation a special feature is added that allows the clock to be generated by writing to the usitc strobe bit. this feature is enabled by write a one to the usiclk bit while setting an external clock source (usics1 = 1). note that even when no wire mode is selected (usiwm1..0 = 0) the external clock input (usck/scl) are can still be used by the counter. bit 76543 210 usisif usioif usipf usidc usicnt3 usicnt2 usicnt1 usicnt0 usisr read/write r/w r/w r/w r r/w r/w r/w r/w initial value 0 0 0 0 0 0 0 0
145 attiny2313/v 2543f?avr?08/04 usi control register ? usicr the control register includes interrupt enable control, wire mode setting, clock select setting, and clock strobe.  bit 7 ? usisie: start condition interrupt enable setting this bit to one enables the start condition detector interrupt. if there is a pending interrupt when the usisie and the global interrupt enable flag is set to one, this will immediately be executed.  bit 6 ? usioie: counter overflow interrupt enable setting this bit to one enables the counter overflow interrupt. if there is a pending inter- rupt when the usioie and the global interrupt enable flag is set to one, this will immediately be executed.  bit 5..4 ? usiwm1..0: wire mode these bits set the type of wire mode to be used. basically only the function of the outputs are affected by these bits. data and clock inputs are not affected by the mode selected and will always have the same func tion. the counter and shift register can therefore be clocked externally, and data input sampled, even when outputs are disabled. the relations between usiwm1..0 and the usi operation is summarized in table 60 on page 146. bit 7 6 5 4 3 2 1 0 usisie usioie usiwm1 usiwm0 us ics1 usics0 usiclk usitc usicr read/write r/w r/w r/w r/w r/w r/w w w initial value 0 0 0 0 0 0 0 0
146 attiny2313/v 2543f?avr?08/04 note: 1. the di and usck pins are renamed to serial data (sda) and serial clock (scl) respectively to avoid confusion between the modes of operation. table 60. relations between usiwm1..0 and the usi operation usiwm1 usiwm0 description 0 0 outputs, clock hold, and start detector disabled. port pins operates as normal. 0 1 three-wire mode. uses do, di, and usck pins. the data output (do) pin overrides the corresponding bit in the port register in this mode. however, the corresponding ddr bit still controls the data direction. when the port pin is set as input the pins pull-up is controlled by the port bit. the data input (di) and serial clock (usck) pins do not affect the normal port operation. when operating as master, clock pulses are software generated by toggling the port register, while the data direction is set to output. the usit c bit in the usicr register can be used for this purpose. 1 0 two-wire mode. uses sda (di) and scl (usck) pins (1) . the serial data (sda) and the serial clock (scl) pins are bi- directional and uses open-collector output drives. the output drivers are enabled by setting the corresponding bit for sda and scl in the ddr register. when the output driver is enabled fo r the sda pin, the output driver will force the line sda low if the output of the shift register or the corresponding bit in the port register is zero. otherwise the sda line will not be driven (i.e., it is released). when the scl pin output driver is enabled the scl line will be forced low if the corresponding bit in the port register is zero, or by the start detector. otherwise the scl line will not be driven. the scl line is held low when a start detector detects a start condition and the output is enabled. clearing the start condition flag (usisif) releases the line. the sda and scl pin inputs is not affected by enabling this mode. pull-ups on the sda and scl port pin are disabled in two-wire mode. 1 1 two-wire mode. uses sda and scl pins. same operation as for the two-wire mode described above, except that the scl line is also held low when a counter overflow occurs, and is held low until the timer overfl ow flag (usioif) is cleared.
147 attiny2313/v 2543f?avr?08/04  bit 3..2 ? usics1..0: clock source select these bits set the clock source for the shift register and counter. the data output latch ensures that the output is changed at the opposite edge of the sampling of the data input (di/sda) when using external clock source (usck/scl). when software strobe or timer0 overflow clock option is selected, the output latch is transparent and therefore the output is changed immediately. clearing the usics1..0 bits enables software strobe option. when using this option, writing a on e to the usiclk bit clocks both the shift register and the counter. for external cloc k source (usics1 = 1), the usiclk bit is no longer used as a strobe, but selects between external clocking and software clocking by the usitc strobe bit. table 61 shows the relationship between the usics1..0 and usiclk setting and clock source used for the shift register and the 4-bit counter.  bit 1 ? usiclk: clock strobe writing a one to this bit location strobes the shift register to shift one step and the counter to increment by one, provided that the usics1..0 bits are set to zero and by doing so the software clock strobe option is selected. the output will change immedi- ately when the clock strobe is executed, i.e., in the same instruction cycle. the value shifted into the shift register is sampled t he previous instruction cycle. the bit will be read as zero. when an external clock source is selected (usics1 = 1), the usiclk function is changed from a clock strobe to a clock select register. setting the usiclk bit in this case will select the usitc strobe bit as clock source for the 4-bit counter (see table 61).  bit 0 ? usitc: toggle clock port pin writing a one to this bit location toggles the usck/scl value either from 0 to 1, or from 1 to 0. the toggling is independent of the setting in the data direction register, but if the port value is to be shown on the pin the ddre4 must be set as output (to one). this feature allows easy clock generation when implementing master devices. the bit will be read as zero. when an external clock source is selected (usics1 = 1) and the usiclk bit is set to one, writing to the usitc str obe bit will directly clock the 4-bit counter. th is allows an early detection of when the transfer is done when operating as a master device. table 61. relations between the usics1..0 and usiclk setting usics1 usics0 usiclk shift register clock source 4-bit counter clock source 0 0 0 no clock no clock 0 0 1 software clock strobe (usiclk) software clock strobe (usiclk) 0 1 x timer/counter0 overflow timer/counter0 overflow 1 0 0 external, positive edge external, both edges 1 1 0 external, negative edge external, both edges 1 0 1 external, positive edge software clock strobe (usitc) 1 1 1 external, negative edge software clock strobe (usitc)
148 attiny2313/v 2543f?avr?08/04 analog comparator the analog comparator compares the input values on the positive pin ain0 and nega- tive pin ain1. when the voltage on the positive pin ain0 is higher than the voltage on the negative pin ain1, the analog comparator output, aco, is set. the comparator?s output can be set to trigger the timer/counter1 input capture function. in addition, the comparator can trigger a separate interrupt, exclusive to the analog comparator. the user can select interrupt triggering on comparator output rise, fall or toggle. a block dia- gram of the comparator and its surrounding logic is shown in figure 65 . figure 65. analog comparator block diagram analog comparator control and status register ? acsr  bit 7 ? acd: analog comparator disable when this bit is written logic one, the power to the analog comparator is switched off. this bit can be set at any time to turn o ff the analog comparator . this will reduce power consumption in active and idle mode. when changing the acd bit, the analog compar- ator interrupt must be disabled by clearing t he acie bit in acsr. otherwise an interrupt can occur when the bit is changed.  bit 6 ? acbg: analog comparator bandgap select when this bit is set, a fixed bandgap referenc e voltage replaces the positive input to the analog comparator. when this bit is cleared, ain0 is applied to the positive input of the analog comparator. see ?internal voltage reference? on page 37.  bit 5 ? aco: analog comparator output the output of the analog comparator is synchronized and then directly connected to aco. the synchronization introduces a delay of 1 - 2 clock cycles.  bit 4 ? aci: analog comparator interrupt flag this bit is set by hardware when a comparator output event triggers the interrupt mode defined by acis1 and acis0. the analog comparator interrupt routine is executed if the acie bit is set and the i-bit in sreg is set. aci is cleared by hardware when execut- ing the corresponding interrupt handling vector. alternatively, aci is cleared by writing a logic one to the flag.  bit 3 ? acie: analog comparator interrupt enable acbg bandgap reference bit 76543210 acd acbg aco aci acie acic acis1 acis0 acsr read/write r/w r/w r r/w r/w r/w r/w r/w initial value 0 0 n/a 0 0 0 0 0
149 attiny2313/v 2543f?avr?08/04 when the acie bit is written logic one and the i-bit in the status register is set, the ana- log comparator interrupt is activated. when written logic zero, the interrupt is disabled.  bit 2 ? acic: analog comparator input capture enable when written logic one, this bit enables the input capture function in timer/counter1 to be triggered by the analog comparator. the comparator output is in this case directly connected to the input capture front-end logic, making the comparator utilize the noise canceler and edge select features of the timer/counter1 input capture interrupt. when written logic zero, no connection between the analog comparator and the input capture function exists. to make the comparator tr igger the timer/counter1 input capture inter- rupt, the icie1 bit in the timer interrupt mask register (timsk) must be set.  bits 1, 0 ? acis1, acis0: analog comparator interrupt mode select these bits determine which comparator events that trigger the analog comparator inter- rupt. the different settings are shown in table 62. when changing the acis1/acis0 bits, the anal og comparator interrupt must be dis- abled by clearing its interrupt enable bit in the acsr register. otherwise an interrupt can occur when the bits are changed. digital input disable register ? didr  bit 1, 0 ? ain1d, ain0d: ain1, ain0 digital input disable when this bit is written logic one, the digital input buffer on the ain1/0 pin is disabled. the corresponding pin register bit will always read as zero when this bit is set. when an analog signal is applied to the ain1/0 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer. table 62. acis1/acis0 settings acis1 acis0 interrupt mode 0 0 comparator interrupt on output toggle. 01reserved 1 0 comparator interrupt on falling output edge. 1 1 comparator interrupt on rising output edge. bit 76543210 ? ? ? ? ? ? ain1d ain0d didr read/writerrrrrrr/wr/w initial value00000000
150 attiny2313/v 2543f?avr?08/04 debugwire on-chip debug system features  complete program flow control  emulates all on-chip func tions, both digital and analog, except reset pin  real-time operation  symbolic debugging support (both at c and assembler source leve l, or for other hlls)  unlimited number of program break po ints (using software break points)  non-intrusive operation  electrical characteristics identical to real device  automatic configuration system  high-speed operation  programming of non-volatile memories overview the debugwire on-chip debug system uses a on e-wire, bi-directional interface to con- trol the program flow, execute avr instructions in the cpu and to program the different non-volatile memories. physical interface when the debugwire enable (dwen) fuse is programmed and lock bits are unpro- grammed, the debugwire system within the target device is activated. the reset port pin is configured as a wire-and (open-drain) bi-directional i/o pin with pull-up enabled and becomes the communication gateway between target and emulator. figure 66. the debugwire setup figure 66 shows the schematic of a target mcu, with debugwire enabled, and the emulator connector. the system clock is not affected by debugwire and will always be the clock source select ed by the cksel fuses. when designing a system where debugwire will be used, the following observations must be made for correct operation:  pull-up resistor on the dw /(reset) line must be larger than 10k. however, the pull- up resistor is optional.  connecting the reset pin directly to v cc will not work. dw gnd dw(reset) vcc 1.8 - 5.5v
151 attiny2313/v 2543f?avr?08/04  capacitors inserted on the reset pin must be disconnected when using debugwire.  all external reset sources must be disconnected. software break points debugwire supports program memory break po ints by the avr break instruction. set- ting a break point in avr studio ? will insert a break inst ruction in the program memory. the instruction replaced by the br eak instruction will be stored. when pro- gram execution is continued, the stored in struction will be executed before continuing from the program memory. a break can be inserted manually by putting the break instruction in the program. the flash must be re-programmed each time a break point is changed. this is auto- matically handled by avr studio through the debugwire interface. the use of break points will therefore reduce the flash data retention. devices used for debugging pur- poses should not be shipped to end customers. limitations of debugwire the debugwire communication pin (dw) is physically located on the same pin as external reset (reset). an external reset source is therefore not supported when the debugwire is enabled. the debugwire system accurately emulates all i/o functions when running at full speed, i.e., when the program in the cpu is running. when the cpu is stopped, care must be taken while accessing some of the i/o registers via the debugger (avr stu- dio). see the debugwire documentation for detailed description of the limitations. a programmed dwen fuse enables some parts of the clock system to be running in all sleep modes. this will increase the power consumption while in sleep. thus, the dwen fuse should be disabled when debugwire is not used. debugwire related register in i/o memory the following section describes the registers used with the debugwire. debugwire data register ? dwdr the dwdr register provides a communica tion channel from the running program in the mcu to the debugger. this register is only accessible by the debugwire and can therefore not be used as a general purpose register in the normal operations. bit 76543210 dwdr[7:0] dwdr read/write r/w r/w r/w r/w r/w r/w r/w r/w initial value00000000
152 attiny2313/v 2543f?avr?08/04 self-programming the flash the device provides a self-programming mechanism for downloading and uploading program code by the mcu itself. the self -programming can use any available data interface and associated protocol to read code and write (program) that code into the program memory. the program memory is updated in a page by page fashion. before programming a page with the data stored in the temporary page buffer, the page must be erased. the temporary page buffer is filled one word at a time using spm and the buffer can be filled either before the page erase command or between a page erase and a page write operation: alternative 1, fill the bu ffer before a page erase  fill temporary page buffer  perform a page erase  perform a page write alternative 2, fill the bu ffer after page erase  perform a page erase  fill temporary page buffer  perform a page write if only a part of the page needs to be changed, the rest of the page must be stored (for example in the temporary page buffer) before the erase, and then be re-written. when using alternative 1, the boot loader provi des an effective read-modify-write feature which allows the user software to first read the page, do the necessary changes, and then write back the modified data. if alternativ e 2 is used, it is not possible to read the old data while loading since the page is already erased. the temporary page buffer can be accessed in a random sequence. it is essential that the page address used in both the page erase and page write operation is addressing the same page. performing page erase by spm to execute page erase, set up the address in the z-pointer, write ?00000011? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage in the z-register. other bits in the z-pointer will be ignored during this operation.  the cpu is halted during the page erase operation. filling the temporary buffer (page loading) to write an instruction word, set up the addre ss in the z-pointer and data in r1:r0, write ?00000001? to spmcsr and execute spm within four clock cycles after writing spmcsr. the content of pcword in the z-register is used to address the data in the temporary buffer. the temporary buffer will auto-erase after a page write operation or by writing the ctpb bit in spmcsr. it is also erased after a system reset. note that it is not possible to write more than one time to each address without erasing the temporary buffer. if the eeprom is written in th e middle of an spm page load operation, a ll data loaded will be lost. performing a page write to execute page write, set up the address in the z-pointer, write ?00000101? to spmcsr and execute spm within four clock cycles after writing spmcsr. the data in r1 and r0 is ignored. the page address must be written to pcpage. other bits in the z-pointer must be written to zero during this operation.  the cpu is halted during the page write operation.
153 attiny2313/v 2543f?avr?08/04 addressing the flash during self- programming the z-pointer is used to address the spm commands. since the flash is organized in pages (see t able 69 on page 159), the program counter can be treated as having two different sections. one section, consisting of the least sig- nificant bits, is addressing the words within a page, while the most significant bits are addressing the pages. this is shown in figure 67. note that the page erase and page write operations are addressed independently. therefore it is of major importance that the software addresses the same page in both the page erase and page write operation. the lpm instruction uses the z-pointer to store the address. since this instruction addresses the flash byte-by-byte, also th e lsb (bit z0) of the z-pointer is used. figure 67. addressing the flash during spm (1) note: 1. the different variables used in figure 67 are listed in table 69 on page 159. bit 151413121110 9 8 zh (r31) z15 z14 z13 z12 z11 z10 z9 z8 zl (r30) z7z6z5z4z3z2z1z0 76543210 program memory 0 1 15 z - register bit 0 zpagemsb word address within a page page address within the flash zpcmsb instruction word pag e pcword[pagemsb:0]: 00 01 02 pageend pag e pcword pcpage pcmsb pagemsb program counter
154 attiny2313/v 2543f?avr?08/04 store program memory control and status register ? spmcsr the store program memory control and status register contains the control bits needed to control the program memory operations.  bits 7..5 ? res: reserved bits these bits are reserved bits in the attiny2313 and always read as zero.  bit 4 ? ctpb: clear temporary page buffer if the ctpb bit is written while filling the temporary page buffer, the temporary page buffer will be cleared a nd the data will be lost.  bit 3 ? rflb: read fuse and lock bits an lpm instruction within three cycles after rflb and selfprgen are set in the spmcsr register, will read either the lock bits or the fuse bits (depending on z0 in the z-pointer) into the destination register. see ?eeprom write prevents writing to spmcsr? on page 155 for details.  bit 2 ? pgwrt: page write if this bit is written to one at the same time as selfprgen, the next spm instruction within four clock cycles executes page writ e, with the data stored in the temporary buffer. the page address is taken from the high part of the z-pointer. the data in r1 and r0 are ignored. the pgwrt bi t will auto-clear upon co mpletion of a page write, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page write operation.  bit 1 ? pgers: page erase if this bit is written to one at the same time as selfprgen, the next spm instruction within four clock cycles executes page eras e. the page address is taken from the high part of the z-pointer. the da ta in r1 and r0 are ignore d. the pgers bit will auto-clear upon completion of a page erase, or if no spm instruction is executed within four clock cycles. the cpu is halted during the entire page write operation.  bit 0 ? selfprgen: self programming enable this bit enables the spm instruction for the next four clock cycles. if written to one together with either ctpb, rflb, pgwrt, or pgers, the follo wing spm instruction will have a special meaning, see description above. if only selfprgen is written, the following spm instruction will store the value in r1:r0 in the temporary page buffer addressed by the z-pointer. the lsb of the z-pointer is ignored. the selfprgen bit will auto-clear upon completion of an spm instru ction, or if no spm instruction is exe- cuted within four clock cycles. during page erase and page write, the selfprgen bit remains high until the operation is completed. writing any other combination than ?10001?, ?01001?, ?00101?, ?00011? or ?00001? in the lower five bits will have no effect. bit 7654321 0 ? ? ? ctpb rflb pgwrt pgers selfprgen spmcsr read/write r r r r/w r/w r/w r/w r/w initial value0000000 0
155 attiny2313/v 2543f?avr?08/04 eeprom write prevents writing to spmcsr note that an eeprom write operation will block all software programming to flash. reading the fuses and lock bits from software will al so be prevented during the eeprom write operation. it is recommended that the user ch ecks the status bit (eewe) in the eecr register and verifies that the bit is cleared before writing to the spmcsr register. reading the fuse and lock bits from software it is possible to read both the fuse and lock bits from software. to read the lock bits, load the z-pointer with 0x0001 and set the rflb and selfprgen bits in spmcsr. when an lpm instruction is executed within three cpu cycles after the rflb and selfprgen bits are set in spmcsr, the value of the lock bits will be loaded in the destination regist er. the rflb and selfprgen bits will auto-clear upon completion of reading the lock bits or if no lpm instruct ion is executed within three cpu cycles or no spm instruction is executed within four cpu cycles. when rflb and selfprgen are cleared, lpm will work as described in the instruction set manual. the algorithm for reading the fuse low byte is similar to the one described above for reading the lock bits. to read the fuse low byte, load the z-pointer with 0x0000 and set the rflb and selfprgen bits in spmcsr. when an lpm instruction is executed within three cycles after the rflb and sel fprgen bits are set in the spmcsr, the value of the fuse low byte (flb) will be loaded in the destination register as shown below. refer to table 68 on page 159 for a detailed description and mapping of the fuse low byte. similarly, when reading the fuse high byte, load 0x0003 in the z-pointer. when an lpm instruction is executed within three cycles after the rflb and selfprgen bits are set in the spmcsr, the value of the fuse high byte (fhb) will be loaded in the destination register as shown below. refer to table xxx on page xxx for detailed description and mapping of the fuse high byte. fuse and lock bits that are programmed, will be read as zero. fuse and lock bits that are unprogrammed, will be read as one. bit 76543210 rd ??????lb2lb1 bit 76543210 rd flb7 flb6 flb5 flb4 flb3 flb2 flb1 flb0 bit 76543210 rd fhb7 fhb6 fhb5 fhb4 fhb3 fhb2 fhb1 fhb0
156 attiny2313/v 2543f?avr?08/04 preventing flash corruption during periods of low v cc , the flash program can be corrupted because the supply volt- age is too low for the cpu and the flash to operate properly. these issues are the same as for board level systems using the flash, and the same design solutions should be applied. a flash program corruption can be caused by two situations when the voltage is too low. first, a regular write sequence to the flash requires a minimum voltage to operate cor- rectly. secondly, the cpu itself can execute in structions incorrectly, if the supply voltage for executing instructions is too low. flash corruption can easily be avoided by following these design recommendations (one is sufficient): 1. keep the avr reset active (low) duri ng periods of insufficient power supply voltage. this can be done by enabling the internal brown-out detector (bod) if the operating voltage matches the detection level. if not, an external low v cc reset protection circuit can be used. if a reset occurs while a write operation is in progress, the write operation will be comp leted provided that the power supply voltage is sufficient. 2. keep the avr core in power-down sleep mode during periods of low v cc . this will prevent the cpu from attempting to decode and execute instructions, effec- tively protecting the spmcsr register and thus the flash from unintentional writes. programming time for flash when using spm the calibrated rc oscilla tor is used to time flash accesses. table 63 shows the typical programming time for flash accesses from the cpu. table 63. spm programming time symbol min programming time max programming time flash write (page erase, page write, and write lock bits by spm) 3.7 ms 4.5 ms
157 attiny2313/v 2543f?avr?08/04 memory programming program and data memory lock bits the attiny2313 provides two lock bits which can be left unprogrammed (?1?) or can be programmed (?0?) to obtain the additional features listed in table 65. the lock bits can only be erased to ?1? with the chip erase command. note: 1. ?1? means unprogrammed, ?0? means programmed notes: 1. program the fuse bits and boot lock bits before programming the lb1 and lb2. 2. ?1? means unprogrammed, ?0? means programmed table 64. lock bit byte (1) lock bit byte bit no de scription default value 7 ? 1 (unprogrammed) 6 ? 1 (unprogrammed) 5 ? 1 (unprogrammed) 4 ? 1 (unprogrammed) 3 ? 1 (unprogrammed) 2 ? 1 (unprogrammed) lb2 1 lock bit 1 (unprogrammed) lb1 0 lock bit 1 (unprogrammed) table 65. lock bit protection modes (1)(2) memory lock bits protection type lb mode lb2 lb1 1 1 1 no memory lock features enabled. 210 further programming of the flash and eeprom is disabled in parallel and serial programming mode. the fuse bits are locked in both serial and parallel programming mode. (1) 300 further programming and verification of the flash and eeprom is disabled in parall el and serial programming mode. the boot lock bits and fuse bits are locked in both serial and parallel programming mode. (1)
158 attiny2313/v 2543f?avr?08/04 fuse bits the attiny2313 has three fuse bytes. table 67 and table 68 describe briefly the func- tionality of all the fuses and how they are mapped into the fuse bytes. note that the fuses are read as logical zero, ?0?, if they are programmed. note: 1. the spien fuse is not accessible in serial programming mode. 2. see ?watchdog timer control register - wdtcsr? on page 41 for details. 3. never ship a product with the dwen fuse programmed regardless of the setting of lock bits. a programmed dwen fuse enables some parts of th e clock system to be running in all sleep modes. this may increase the power consumption. 4. see table 16 on page 34 for bodlevel fuse decoding. 5. see ?alternate functions of port a? on page 52 for description of rstdisbl fuse. table 66. fuse extended byte fuse extended byte bit no description default value 7 ? 1 (unprogrammed) 6 ? 1 (unprogrammed) 5 ? 1 (unprogrammed) 4 ? 1 (unprogrammed) 3 ? 1 (unprogrammed) 2 ? 1 (unprogrammed) 1 ? 1 (unprogrammed) selfprgen 0 self programming enable 1 (unprogrammed) table 67. fuse high byte fuse high byte bit no description default value dwen (3) 7 debugwire enable 1 (unprogrammed) eesave 6 eeprom memory is preserved through the chip erase 1 (unprogrammed, eeprom not preserved) spien (1) 5 enable serial program and data downloading 0 (programmed, spi prog. enabled) wdton (2) 4 watchdog timer always on 1 (unprogrammed) bodlevel2 (4) 3 brown-out detector trigger level 1 (unprogrammed) bodlevel1 (4) 2 brown-out detector trigger level 1 (unprogrammed) bodlevel0 (4) 1 brown-out detector trigger level 1 (unprogrammed) rstdisbl (5) 0 external reset disable 1 (unprogrammed)
159 attiny2313/v 2543f?avr?08/04 note: 1. the default value of sut1..0 results in maximum start-up time for the default clock source. see table 15 on page 33 for details. 2. the default setting of cksel3..0 results in internal rc oscillator @ 8 mhz. the status of the fuse bits is not affected by chip erase. note that the fuse bits are locked if lock bit1 (lb1) is programmed. program the fuse bits before programming the lock bits. latching of fuses the fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves programming mode. this does not apply to the eesave fuse which will take effect once it is programmed. the fuses are also latched on power-up in normal mode. signature bytes all atmel microcontrollers have a three-byte signature code which identifies the device. this code can be read in both serial and parallel mode, also when the device is locked. the three bytes reside in a separate address space. for the attiny2313 the signature bytes are: 1. 0x000: 0x1e (indicates manufactured by atmel). 2. 0x001: 0x91 (indicates 2kb flash memory). 3. 0x002: 0x0a (indicates attiny2 313 device when 0x001 is 0x91). calibration byte the attiny2313 st ores two different calibration valu es for the internal rc oscillator. these bytes resides in the high byte of address 0x0000 and 0x0001 in the signature address space for 4 and 8 mhz respectively. du ring reset, the 4 mhz value is automati- cally written to the ?oscillator calibration register ? osccal? on page 25, to ensure correct frequency of th e calibrated rc oscillator. page size table 68. fuse low byte fuse low byte bit no description default value ckdiv8 7 divide clock by 8 0 (programmed) ckout 6 output clock on ckout pin 1 (unprogrammed) sut1 5 select start-up time 1 (unprogrammed) (1) sut0 4 select start-up time 0 (programmed) (1) cksel3 3 select clock source 0 (programmed) (2) cksel2 2 select clock source 0 (programmed) (2) cksel1 1 select clock source 1 (unprogrammed) (2) cksel0 0 select clock source 0 (programmed) (2) table 69. no. of words in a page and no. of pages in the flash flash size page size pcword no. of pages pcpage pcmsb 1k words (2k bytes) 16 words pc[3:0] 64 pc[9:4] 9
160 attiny2313/v 2543f?avr?08/04 parallel programming parameters, pin mapping, and commands this section describes how to parallel program and verify flash program memory, eeprom data memory, memory lo ck bits, and fuse bits in the attiny2313. pulses are assumed to be at least 250 ns unless otherwise noted. signal names in this section, some pins of the attiny23 13 are referenced by signal names describing their functionality during parallel programming, see figure 68 and table 71. pins not described in the following table are referenced by pin names. the xa1/xa0 pins determine the action executed when the xtal1 pin is given a posi- tive pulse. the bit coding is shown in table 73. when pulsing wr or oe , the command loaded determines the action executed. the dif- ferent commands are shown in table 74. figure 68. parallel programming table 70. no. of words in a page and no. of pages in the eeprom eeprom size page size pcword no. of pages pcpage eeamsb 128 bytes 4 bytes eea[1:0] 32 eea[6:2] 6 table 71. pin name mapping signal name in programming mode pin name i/o function rdy/bsy pd1 o 0: device is busy programming, 1: device is ready for new command. oe pd2 i output enable (active low). wr pd3 i write pulse (active low). bs1/pagel pd4 i byte select 1 (?0? selects low byte, ?1? selects high byte). program memory and eeprom data page load. vcc +5v gnd xtal1 pd1 pd2 pd3 pd4 pd5 pd6 pb7 - pb0 data i/o reset +12 v bs1/pagel xa0 xa1/bs2 oe rdy/bsy wr
161 attiny2313/v 2543f?avr?08/04 xa0 pd5 i xtal action bit 0 xa1/bs2 pd6 i xtal action bit 1. byte select 2 (?0? selects low byte, ?1? selects 2?nd high byte). data i/o pb7-0 i/o bi-directio nal data bus (output when oe is low). table 72. pin values used to enter programming mode pin symbol value xa1 prog_enable[3] 0 xa0 prog_enable[2] 0 bs1 prog_enable[1] 0 wr prog_enable[0] 0 table 73. xa1 and xa0 coding xa1 xa0 action when xtal1 is pulsed 0 0 load flash or eeprom address (high or low address byte determined by bs1). 0 1 load data (high or low data byte for flash determined by bs1). 1 0 load command 1 1 no action, idle table 74. command byte bit coding command byte command executed 1000 0000 chip erase 0100 0000 write fuse bits 0010 0000 write lock bits 0001 0000 write flash 0001 0001 write eeprom 0000 1000 read signature bytes and calibration byte 0000 0100 read fuse and lock bits 0000 0010 read flash 0000 0011 read eeprom table 71. pin name mapping (continued) signal name in programming mode pin name i/o function
162 attiny2313/v 2543f?avr?08/04 serial programming pin mapping parallel programming enter programming mode the following algorithm puts the device in parallel programming mode: 1. apply 4.5 - 5.5v between v cc and gnd. 2. set reset to ?0? and toggle xtal1 at least six times. 3. set the prog_enable pins listed in table 72 on page 161 to ?0000? and wait at least 100 ns. 4. apply 11.5 - 12.5v to reset . any activity on prog_enable pins within 100 ns after +12v has been applied to reset , will cause the device to fail entering pro- gramming mode. 5. wait at least 50 s before sending a new command. note: if the reset pin is disabled by programming the rstdisbl fuse, it may not be possible to follow the proposed algorithm above. the same may apply when external crystal or external rc configuration is selected because it is not possible to apply qualified xtal1 pulses. in such cases, the following algorithm should be followed: 1. set prog_enable pins listed in table 72 on page 161 to ?0000?. 2. apply 4.5 - 5.5v between v cc and gnd simultanously as 11.5 - 12.5v is applied to reset . 3. wait 100 ns. 4. re-program the fuses to ensure that exte rnal clock is selected as clock source (cksel3:0 = 0b0000) and reset pin is activated (rstdisbl unprogrammed). if lock bits are programmed, a chip erase command must be executed before changing the fuses. 5. exit programming mode by power the device down or by bringing reset pin to 0b0. entering programming mode with the original algorithm, as described above. considerations for efficient programming the loaded command and address are retained in the device during programming. for efficient programming, the following should be considered.  the command needs only be loaded once when writing or reading multiple memory locations.  skip writing the data value 0xff, that is the contents of the entire eeprom (unless the eesave fuse is programmed) and flash after a chip erase.  address high byte needs only be loaded before programming or reading a new 256 word window in flash or 256 byte eeprom . this consideration also applies to signature bytes reading. chip erase the chip erase will er ase the flash and eeprom (1) memories plus lock bits. the lock bits are not reset until the program memory has been completely erased. the fuse bits table 75. pin mapping serial programming symbol pins i/o description mosi pb5 i serial data in miso pb6 o serial data out sck pb7 i serial clock
163 attiny2313/v 2543f?avr?08/04 are not changed. a chip erase must be performed before the flash and/or eeprom are reprogrammed. note: 1. the eeprpom memory is preserved du ring chip erase if the eesave fuse is programmed. load command ?chip erase? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?1000 0000?. this is the command for chip erase. 4. give xtal1 a positive pulse. this loads the command. 5. give wr a negative pulse. this starts the chip erase. rdy/bsy goes low. 6. wait until rdy/bsy goes high before loading a new command.
164 attiny2313/v 2543f?avr?08/04 programming the flash the flash is organized in pages, see tabl e 69 on page 159. when programming the flash, the program data is latched into a page buffer. this allows one page of program data to be programmed simultaneously. the following procedure describes how to pro- gram the entire flash memory: a. load command ?write flash? 1. set xa1, xa0 to ?10?. this enables command loading. 2. set bs1 to ?0?. 3. set data to ?0001 0000?. this is the command for write flash. 4. give xtal1 a positive pulse. this loads the command. b. load address low byte 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs1 to ?0?. this selects low address. 3. set data = address low byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address low byte. c. load data low byte 1. set xa1, xa0 to ?01?. this enables data loading. 2. set data = data low byte (0x00 - 0xff). 3. give xtal1 a positive pulse. this loads the data byte. d. load data high byte 1. set bs1 to ?1?. this selects high data byte. 2. set xa1, xa0 to ?01?. this enables data loading. 3. set data = data high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the data byte. e. latch data 1. set bs1 to ?1?. this selects high data byte. 2. give pagel a positive pulse. this latches the data bytes. (see figure 70 for sig- nal waveforms) f. repeat b through e until the entire buffer is filled or until all data within the page is loaded. while the lower bits in the address are mapped to words within the page, the higher bits address the pages within the flash. this is illustrated in figure 69 on page 165. note that if less than eight bits are required to address words in the page (pagesize < 256), the most significant bit(s) in the address low byte are used to address the page when performing a page write. g. load address high byte 1. set xa1, xa0 to ?00?. this enables address loading. 2. set bs1 to ?1?. this selects high address. 3. set data = address high byte (0x00 - 0xff). 4. give xtal1 a positive pulse. this loads the address high byte. h. program page 1. give wr a negative pulse. this starts programming of the entire page of data. rdy/bsy goes low. 2. wait until rdy/bsy goes high (see figure 70 for signal waveforms).
165 attiny2313/v 2543f?avr?08/04 i. repeat b through h until the entire flash is programmed or until all data has been programmed. j. end page programming 1. 1. set xa1, xa0 to ?10?. this enables command loading. 2. set data to ?0000 0000?. this is the command for no operation. 3. give xtal1 a positive pulse. this loads the command, and the internal write sig- nals are reset. figure 69. addressing the flash which is organized in pages (1) note: 1. pcpage and pcword are listed in table 69 on page 159. figure 70. programming the flash waveforms (1) note: 1. ?xx? is don?t care. the letters re fer to the programming description above. program memory word address within a page page address within the flash instruction word pag e pcword[pagemsb:0]: 00 01 02 pageend pag e pcword pcpage pcmsb pagemsb program counter rdy/bsy wr oe reset +12v pagel bs2 0x10 addr. low addr. high data data low data high addr. low data low data high xa1 xa0 bs1 xtal1 xx xx xx abcdeb cdegh f
166 attiny2313/v 2543f?avr?08/04 programming the eeprom the eeprom is organized in pages, see table 70 on page 160. when programming the eeprom, the program data is latched into a page buffer . this allows one page of data to be programmed simultaneously. the programming algorithm for the eeprom data memory is as follows (refer to ?programming the flash? on page 164 for details on command, address and data loading): 1. a: load command ?0001 0001?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. c: load data (0x00 - 0xff). 5. e: latch data (give pagel a positive pulse). k: repeat 3 through 5 until the entire buffer is filled. l: program eeprom page 1. set bs to ?0?. 2. give wr a negative pulse. this starts programming of the eeprom page. rdy/bsy goes low. 3. wait until to rdy/bsy goes high before programming the next page (see figure 71 for signal waveforms). figure 71. programming the eeprom waveforms reading the flash the algorithm for reading the flash memory is as follows (refer to ?programming the flash? on page 164 for details on command and address loading): 1. a: load command ?0000 0010?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the flash word low byte can now be read at data. 5. set bs to ?1?. the flash word high byte can now be read at data. 6. set oe to ?1?. rdy/bsy wr oe reset +12v pagel bs2 0x11 addr. high data addr. low data addr. low data xx xa1 xa0 bs1 xtal1 xx agbceb c el k
167 attiny2313/v 2543f?avr?08/04 reading the eeprom the algorithm for readi ng the eeprom memory is as follows (refer to ?programming the flash? on page 164 for details on command and address loading): 1. a: load command ?0000 0011?. 2. g: load address high byte (0x00 - 0xff). 3. b: load address low byte (0x00 - 0xff). 4. set oe to ?0?, and bs1 to ?0?. the eeprom data byte can now be read at data. 5. set oe to ?1?. programming the fuse low bits the algorithm for programming the fuse low bits is as follows (refer to ?programming the flash? on page 164 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. give wr a negative pulse and wait for rdy/bsy to go high. programming the fuse high bits the algorithm for programming the fuse high bits is as follows (refer to ?programming the flash? on page 164 for details on command and data loading): 1. a: load command ?0100 0000?. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. set bs1 to ?1? and bs2 to ?0?. this selects high data byte. 4. give wr a negative pulse and wait for rdy/bsy to go high. 5. set bs1 to ?0?. this selects low data byte. programming the extended fuse bits the algorithm for programming the extended fuse bits is as follows (refer to ?program- ming the flash? on page 164 for details on command and data loading): 1. 1. a: load command ?0100 0000?. 2. 2. c: load data low byte. bit n = ?0? programs and bit n = ?1? erases the fuse bit. 3. 3. set bs1 to ?0? and bs2 to ?1?. this selects extended data byte. 4. 4. give wr a negative pulse and wait for rdy/bsy to go high. 5. 5. set bs2 to ?0?. this selects low data byte. figure 72. programming the fuses waveforms rdy/bsy wr oe reset +12v pagel 0x40 data data xx xa1 xa0 bs1 xtal1 ac 0x40 data xx ac write fuse low byte write fuse high byte 0x40 data xx ac write extended fuse byte bs2
168 attiny2313/v 2543f?avr?08/04 programming the lock bits the algorithm for programming the lock bits is as follows (refer to ?programming the flash? on page 164 for details on command and data loading): 1. a: load command ?0010 0000?. 2. c: load data low byte. bit n = ?0? programs the lock bit. if lb mode 3 is pro- grammed (lb1 and lb2 is programmed), it is not possible to program the boot lock bits by any external programming mode. 3. give wr a negative pulse and wait for rdy/bsy to go high. the lock bits can only be cleared by executing chip erase. reading the fuse and lock bits the algorithm for reading the fuse and lock bits is as follows (refer to ?programming the flash? on page 164 for details on command loading): 1. a: load command ?0000 0100?. 2. set oe to ?0?, bs2 to ?0? and bs1 to ?0?. the status of the fuse low bits can now be read at data (?0? means programmed). 3. set oe to ?0?, bs2 to ?1? and bs1 to ?1?. the status of the fuse high bits can now be read at data (?0? means programmed). 4. set oe to ?0?, bs2 to ?1?, and bs1 to ?0?. the status of the extended fuse bits can now be read at data (?0? means programmed). 5. set oe to ?0?, bs2 to ?0? and bs1 to ?1?. the status of the lock bits can now be read at data (?0? means programmed). 6. set oe to ?1?. figure 73. mapping between bs1, bs2 and the fuse and lock bits during read reading the signature bytes the algorithm for reading the signature bytes is as follows (refer to ?programming the flash? on page 164 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte (0x00 - 0x02). 3. set oe to ?0?, and bs to ?0?. the selected signature byte can now be read at data. 4. set oe to ?1?. lock bits 0 1 bs2 fuse high byte 0 1 bs1 data fuse low byte 0 1 bs2 extended fuse byte
169 attiny2313/v 2543f?avr?08/04 reading the calibration byte the algorithm for reading the calibration byte is as follows (refer to ?programming the flash? on page 164 for details on command and address loading): 1. a: load command ?0000 1000?. 2. b: load address low byte, 0x00. 3. set oe to ?0?, and bs1 to ?1?. the calibration byte can now be read at data. 4. set oe to ?1?. parallel programming characteristics figure 74. parallel programming timing, including some general timing requirements figure 75. parallel programming timing, loading sequence with timing requirements (1) note: 1. the timing requirements shown in figure 74 (i.e., t dvxh , t xhxl , and t xldx ) also apply to loading operation. data & contol (data, xa0/1, bs1, bs2) xtal1 t xhxl t wlwh t dvxh t xldx t plwl t wlrh wr rdy/bsy pagel t phpl t plbx t bvph t xlwl t wlbx t bvwl wlrl xtal1 pagel t plxh xlxh t t xlph addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) load data (low byte) load data (high byte) load data load address (low byte)
170 attiny2313/v 2543f?avr?08/04 figure 76. parallel programming timing, reading sequence (within the same page) with timing requirements (1) note: 1. the timing requirements shown in figure 74 (i.e., t dvxh , t xhxl , and t xldx ) also apply to reading operation. table 76. parallel programming characteristics, v cc = 5v 10% symbol parameter min typ max units v pp programming enable voltage 11.5 12.5 v i pp programming enable current 250 a t dvxh data and control valid before xtal1 high 67 ns t xlxh xtal1 low to xtal1 high 200 ns t xhxl xtal1 pulse width high 150 ns t xldx data and control hold after xtal1 low 67 ns t xlwl xtal1 low to wr low 0 ns t xlph xtal1 low to pagel high 0 ns t plxh pagel low to xtal1 high 150 ns t bvph bs1 valid before pagel high 67 ns t phpl pagel pulse width high 150 ns t plbx bs1 hold after pagel low 67 ns t wlbx bs2/1 hold after wr low 67 ns t plwl pagel low to wr low 67 ns t bvwl bs1 valid to wr low 67 ns t wlwh wr pulse width low 150 ns t wlrl wr low to rdy/bsy low 0 1 s t wlrh wr low to rdy/bsy high (1) 3.7 4.5 ms t wlrh_ce wr low to rdy/bsy high for chip erase (2) 7.5 9 ms t xlol xtal1 low to oe low 0 ns xtal1 oe addr0 (low byte) data (low byte) data (high byte) addr1 (low byte) data bs1 xa0 xa1 load address (low byte) read data (low byte) read data (high byte) load address (low byte) t bvdv t oldv t xlol t ohdz
171 attiny2313/v 2543f?avr?08/04 notes: 1. t wlrh is valid for the write flash, write eeprom, write fuse bits and write lock bits commands. 2. t wlrh_ce is valid for the chip erase command. serial downloading both the flash and eeprom memory arrays can be programmed using the serial spi bus while reset is pulled to gnd. the serial interface consists of pins sck, mosi (input) and miso (o utput). after reset is set low, the programming enable instruction needs to be executed first before program/ erase operations can be executed. note, in table 75 on page 162, the pin mapping for spi programming is listed. not all parts use the spi pins dedicated for the internal spi interface. figure 77. serial programming and verify (1) notes: 1. if the device is clocked by the inter nal oscillator, it is no need to connect a clock source to the xtal1 pin. 2. v cc - 0.3v < avcc < v cc + 0.3v, however, avcc should always be within 1.8 - 5.5v when programming the eeprom, an auto-erase cy cle is built into the self-timed pro- gramming operation (in the serial mode only ) and there is no need to first execute the chip erase instruction. the chip erase operation turns the content of every memory location in both the program and eeprom arrays into 0xff. depending on cksel fuses, a valid clock must be present. the minimum low and high periods for the serial clock (sck) input are defined as follows: low:> 2 cpu clock cycles for f ck < 12 mhz, 3 cpu clock cycles for f ck >= 12 mhz high:> 2 cpu clock cycles for f ck < 12 mhz, 3 cpu clock cycles for f ck >= 12 mhz t bvdv bs1 valid to data valid 0 250 ns t oldv oe low to data valid 250 ns t ohdz oe high to data tri-stated 250 ns table 76. parallel programming characteristics, v cc = 5v 10% (continued) symbol parameter min typ max units vcc gnd xtal1 sck miso mosi reset +1.8 - 5.5v
172 attiny2313/v 2543f?avr?08/04 serial programming algorithm when writing serial data to the attiny2313, da ta is clocked on the rising edge of sck. when reading data from the attiny2313, data is clocked on the falling edge of sck. see figure 78, figure 79 and table 79 for timing details. to program and verify the attiny2313 in the serial programming mode, the following sequence is recommended (see four byte instruction formats in table 78 on page 173 ): 1. power-up sequence: apply power between v cc and gnd while reset and sck are set to ?0?. in some systems, the programmer can not guarantee that sck is held low during power-up. in this case, reset must be given a positive pulse of at least two cpu clock cycles duration after sck has been set to ?0?. 2. wait for at least 20 ms and enable serial programming by sending the program- ming enable serial instruction to pin mosi. 3. the serial programming instructions will not work if the communication is out of synchronization. when in sync. the second byte (0x53), will echo back when issuing the third byte of the programming enable instruction. whether the echo is correct or not, all four bytes of the instruction must be transmitted. if the 0x53 did not echo back, give reset a positive pulse and issue a new programming enable command. 4. the flash is programmed one page at a time. the memory page is loaded one byte at a time by supplying the 4 lsb of the address and data together with the load program memory page instruction. to ensure correct loading of the page, the data low byte must be loaded before data high byte is applied for a given address. the program memory page is stored by loading the write program memory page instruction with the 6 msb of the address. if polling ( rdy/bsy ) is not used, the user must wait at least t wd_flash before issuing the next page. (see table 77 on page 173.) accessing the serial programming interface before the flash write operation completes can result in incorrect programming. 5. a: the eeprom array is programmed one byte at a time by supplying the address and data to gether with the appr opriate write instruction. an eeprom memory location is first automatically er ased before new data is written. if polling (rdy/bsy ) is not used, the user must wait at least t wd_eeprom before issuing the next byte. (see table 77 on page 173.) in a chip erased device, no 0xffs in the data file(s) need to be programmed. b: the eeprom array is programmed one pa ge at a time. the memory page is loaded one byte at a time by supplying the 2 lsb of the address and data together with the load eeprom memory page in struction. the eeprom mem- ory page is stored by loading the wr ite eeprom memory page instruction with the 5 msb of the address. when usin g eeprom page access only byte loca- tions loaded with the load eeprom memory page instruction is altered. the remaining locations rema in unchanged. if polling ( rdy/bsy ) is not used, the used must wait at least t wd_eeprom before issuing the next page (see table 77 on page 173). in a chip erased device, no 0xff in the data file(s) need to be programmed. 6. any memory location can be verified by using the read instruction which returns the content at the selected address at serial output miso. 7. at the end of the programming session, reset can be set high to commence normal operation. 8. power-off sequence (if needed): set reset to ?1?. tu r n v cc power off.
173 attiny2313/v 2543f?avr?08/04 figure 78. serial programm ing waveforms table 77. minimum wait delay befo re writing the next flash or eeprom location symbol minimum wait delay t wd_flash 4.5 ms t wd_eeprom 4.0 ms t wd_erase 4.0 ms t wd_fuse 4.5 ms msb msb lsb lsb serial clock input (sck) serial data input (mosi) (miso) sample serial data output table 78. serial programming instruction set instruction instruction format operation byte 1 byte 2 byte 3 byte4 programming enable 1010 1100 0101 0011 xxxx xxxx xxxx xxxx enable serial programming after reset goes low. chip erase 1010 1100 100x xxxx xxxx xxxx xxxx xxxx chip erase eeprom and flash. read program memory 0010 h 000 0000 00 aa bbbb bbbb oooo oooo read h (high or low) data o from program memory at word address a : b . load program memory page 0100 h 000 000x xxxx xxxx bbbb iiii iiii write h (high or low) data i to program memory page at word address b . data low byte must be loaded before data high byte is applied within the same address. write program memory page 0100 1100 0000 00 aa bbbb xxxx xxxx xxxx write program memory page at address a : b . read eeprom memory 1010 0000 000x xxxx x bbb bbbb oooo oooo read data o from eeprom memory at address b . write eeprom memory 1100 0000 000x xxxx x bbb bbbb iiii iiii write data i to eeprom memory at address b . load eeprom memory page (page access) 1100 0001 0000 0000 0000 00 bb iiii iiii load data i to eeprom memory page buffer. after data is loaded, program eeprom page. write eeprom memory page (page access) 1100 0010 00xx xxxx x bbb bb 00 xxxx xxxx write eeprom page at address b .
174 attiny2313/v 2543f?avr?08/04 note: a = address high bits, b = address low bits, h = 0 - low byte, 1 - high byte, o = data out, i = data in, x = don?t care read lock bits 0101 1000 0000 0000 xxxx xxxx xx oo oooo read lock bits. ?0? = programmed, ?1? = unprogrammed. see table 64 on page 157 for details. write lock bits 1010 1100 111x xxxx xxxx xxxx 11 ii iiii write lock bits. set bits = ?0? to program lock bits. see table 64 on page 157 for details. read signature byte 0011 0000 000x xxxx xxxx xx bb oooo oooo read signature byte o at address b . write fuse bits 1010 1100 1010 0000 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. write fuse high bits 1010 1100 1010 1000 xxxx xxxx iiii iiii set bits = ?0? to program, ?1? to unprogram. write extended fuse bits 1010 1100 1010 0100 xxxx xxxx xxxx xxx i set bits = ?0? to program, ?1? to unprogram. read fuse bits 0101 0000 0000 0000 xxxx xxxx oooo oooo read fuse bits. ?0? = programmed, ?1? = unprogrammed. read fuse high bits 0101 1000 0000 1000 xxxx xxxx oooo oooo read fuse high bits. ?0? = pro- grammed, ?1? = unprogrammed. read extended fuse bits 0101 0000 0000 1000 xxxx xxxx oooo oooo read extended fuse bits. ?0? = pro- grammed, ?1? = unprogrammed. read calibration byte 0011 1000 000x xxxx 0000 000 b oooo oooo read calibration byte at address b . poll rdy/bsy 1111 0000 0000 0000 xxxx xxxx xxxx xxx o if o = ?1?, a programming operation is still busy. wait until this bit returns to ?0? before applying another command. table 78. serial programming instruction set instruction instruction format operation byte 1 byte 2 byte 3 byte4
175 attiny2313/v 2543f?avr?08/04 serial programming characteristics figure 79. serial programming timing note: 1. 2 t clcl for f ck < 12 mhz, 3 t clcl for f ck >= 12 mhz table 79. serial programming characteristics, t a = -40 c to 85 c, v cc = 2.7v - 5.5v (unless otherwise noted) symbol parameter min typ max units 1/t clcl oscillator frequency (attiny2313l) 0 8 mhz t clcl oscillator period (attiny2313l) 125 ns 1/t clcl oscillator frequency (attiny2313, v cc = 4.5v - 5.5v) 0 16 mhz t clcl oscillator period (attiny2313, v cc = 4.5v - 5.5v) 67 ns t shsl sck pulse width high 2 t clcl * ns t slsh sck pulse width low 2 t clcl * ns t ovsh mosi setup to sck high t clcl ns t shox mosi hold after sck high 2 t clcl ns t sliv sck low to miso valid tbd tbd tbd ns mosi miso sck t ovsh t shsl t slsh t shox t sliv
176 attiny2313/v 2543f?avr?08/04 electrical characteristics absolute maximum ratings* dc characteristics notes: 1. all dc characteristics contained in this data sheet ar e based on simulation and characterization of other avr microcont rol- lers manufactured in the same process technology. these valu es are preliminary values repr esenting design targets, and will be updated after characterization of actual silicon. 2. ?max? means the highest value where the pin is guaranteed to be read as low. operating temperature.................................. -55 c to +125 c *notice: stresses beyond those listed under ?absolute maximum ratings? may cause permanent dam- age to the device. this is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of th is specification is not implied. exposure to absolute maximum rating conditions for extended periods may affect device reliability. storage temperature ..................................... -65c to +150c voltage on any pin except reset with respect to ground ................................-0.5v to v cc +0.5v voltage on reset with respect to ground......-0.5v to +13.0v maximum operating voltage ............................................ 6.0v dc current per i/o pin ............................................... 40.0 ma dc current v cc and gnd pins................................ 200.0 ma t a = -40 c to 85 c, v cc = 1.8v to 5.5v (unless otherwise noted) (1) symbol parameter condition min. typ. max. units v il input low voltage -0.5 0.2v cc v v ih input high-voltage except reset pin 0.6v cc (3) v cc +0.5 v v ih2 input high-voltage reset pin 0.9v cc (3) v cc +0.5 v v ol output low voltage (4) (port b) i ol = 10 ma, v cc = 5v i ol = 5 ma, v cc = 3v 0.7 0.5 v v v oh output high-voltage (5) (port b) i oh = -10 ma, v cc = 5v i oh = -5 ma, v cc = 3v 4.2 2.5 v v i il input leakage current i/o pin vcc = 5.5 v, p i n l o w (absolute value) 1a i ih input leakage current i/o pin vcc = 5.5 v, pin high (absolute value) 1a r rst reset pull-up resistor 30 60 k ? r pu i/o pin pull-up resistor 20 50 k ? i cc power supply current active 1mhz, v cc = 2v 0.35 ma active 4mhz, v cc = 3v 2 ma active 8mhz, v cc = 5v 6 ma idle 1mhz, v cc = 2v 0.08 0.2 ma idle 4mhz, v cc = 3v 0.41 1 ma idle 8mhz, v cc = 5v 1.6 3 ma power-down mode wdt enabled, v cc = 3v < 3 6 a wdt disabled, v cc = 3v < 0.5 2 a
177 attiny2313/v 2543f?avr?08/04 3. ?min? means the lowest value where t he pin is guaranteed to be read as high. 4. although each i/o port can sink more than the test conditions (10 ma at v cc = 5v, 5 ma at v cc = 3v) under steady state conditions (non-transient), th e following must be observed: 1] the sum of all iol, for a ll ports, should not exceed 60 ma. if iol exceeds the test condition, vol may exceed the related specification. pins are not guar anteed to sink current greater than the listed test condition. 5. although each i/o port can source more than the test conditions (10 ma at v cc = 5v, 5 ma at v cc = 3v) under steady state conditions (non-transient), th e following must be observed: 1] the sum of all ioh, for a ll ports, should not exceed 60 ma. if ioh exceeds the test condition, voh may exceed the rela ted specification. pins are not guaranteed to source current greater than the listed test condition. external clock drive waveforms figure 80. external clock drive waveforms external clock drive v il1 v ih1 table 80. external clock drive (estimated values) symbol parameter v cc = 1.8 - 5.5v v cc = 4.5 - 5.5v units min. max. min. max. min. max. 1/t clcl oscillator frequency 0108016mhz t clcl clock period 1000 125 62.5 ns t chcx high time 400 50 25 ns t clcx low time 400 50 25 ns t clch rise time 2.0 1.6 0.5 s t chcl fall time 2.0 1.6 0.5 s ? t clcl change in period from one clock cycle to the next 22 2%
178 attiny2313/v 2543f?avr?08/04 maximum speed vs. v cc maximum frequency is dependent on v cc. as shown in figure 81 and figure 82, the maximum frequency vs. v cc curve is linear between 1.8v < v cc < 2.7v and between 2.7v < v cc < 4.5v. figure 81. maximum frequency vs. v cc , attiny2313v figure 82. maximum frequency vs. v cc , attiny2313 10 mhz 4 mhz 1.8v 2.7v 5.5v safe operating area 20 mhz 10 mhz 2.7v 4.5v 5.5v safe operating area
179 attiny2313/v 2543f?avr?08/04 attiny2313 typical characteristics the following charts show typical behavior. these figures are not tested during manu- facturing. all current consumption measurements are performed with all i/o pins configured as inputs and with internal pull-ups enabled. a sine wave generator with rail- to-rail output is used as clock source. the power consumption in power-down mode is independent of clock selection. the current consumption is a function of several factors such as: operating voltage, operating frequency, loading of i/o pins, switching rate of i/o pins, code executed and ambient temperature. the dominating factors are operating voltage and frequency. the current drawn from capacitive loaded pins may be estimated (for one pin) as c l * v cc *f where c l = load capacitance, v cc = operating voltage and f = average switch- ing frequency of i/o pin. the parts are characterized at frequencies higher than test limits. parts are not guaran- teed to function properly at frequencies higher than the ordering code indicates. the difference between current consumption in power-down mode with watchdog timer enabled and power-down mode with watchdog timer disabled represents the dif- ferential current drawn by the watchdog timer. values are estimates. all values are subject to change. active supply current figure 83. active supply current vs. frequency (0.1 - 1.0 mhz) active supply current vs. low frequency 0.1 - 1.0 mhz 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 1.8 v 0 0.2 0.4 0.6 0.8 1 1.2 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 frequency (mhz) i cc (ma)
180 attiny2313/v 2543f?avr?08/04 figure 84. active supply current vs. frequency (1 - 20 mhz) figure 85. active supply current vs. v cc (internal rc oscillator, 8 mhz) active supply current vs. frequency 1 - 20 mhz 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 1.8 v 0 2 4 6 8 10 12 14 02468101214161820 frequency (mhz) i cc (ma) active supply current vs. v cc internal rc oscillator, 8 mhz 85 ?c 25 ?c -40 ?c 0 1 2 3 4 5 6 7 8 9 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma)
181 attiny2313/v 2543f?avr?08/04 figure 86. active supply current vs. v cc (internal rc oscillator, 4 mhz) figure 87. active supply current vs. v cc (internal rc oscillator, 1 mhz) active supply current vs. v cc internal rc oscillator, 4 mhz 85 c 25 c -40 c 0 1 2 3 4 5 6 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) active supply current vs. v cc internal rc oscillator, 1 mhz 85 c 25 c -40 c 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma)
182 attiny2313/v 2543f?avr?08/04 figure 88. active supply current vs. v cc (internal rc osc illator, 0.5 mhz) figure 89. active supply current vs. v cc (internal rc oscillator, 128 khz) active supply current vs. v cc internal rc oscillator, 0.5 mhz 85 c 25 c -40 c 0 0.2 0.4 0.6 0.8 1 1.2 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) active supply current vs. v cc internal rc oscillator, 128 khz 85 c 25 c -40 c 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 1.5 2 2.5 3 3.5 4 4.5 5 5.5 6 v cc (v) i cc (ma)
183 attiny2313/v 2543f?avr?08/04 idle supply current figure 90. idle supply current vs. frequency (0.1 - 1.0 mhz) figure 91. idle supply current vs. frequency (1 - 20 mhz) idle supply current vs. frequency 0.1 - 1.0 mhz 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 1.8 v 0 0.05 0.1 0.15 0.2 0.25 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 frequency (mhz) i cc (m a) idle supply current vs. frequency 1 - 20 mhz 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 1.8 v 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 0 2 4 6 8 101214161820 frequency (mhz) i cc (ma)
184 attiny2313/v 2543f?avr?08/04 figure 92. idle supply current vs. v cc (internal rc oscillator, 8 mhz) figure 93. idle supply current vs. v cc (internal rc oscillator, 4 mhz) idle supply current vs. v cc internal rc oscillator, 8 mhz 85 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) idle supply current vs. v cc internal rc oscillator, 4 mhz 85 c 25 c -40 c 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma)
185 attiny2313/v 2543f?avr?08/04 figure 94. idle supply current vs. v cc (internal rc oscillator, 1 mhz) figure 95. idle supply current vs. v cc (internal rc osc illator, 0.5 mhz) idle supply current vs. v cc internal rc oscillator, 1 mhz 85 c 25 c -40 c 0 0.1 0.2 0.3 0.4 0.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma) idle supply current vs. v cc internal rc oscillator, 0.5 mhz 85 c 25 c -40 c 0 0.05 0.1 0.15 0.2 0.25 0.3 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma)
186 attiny2313/v 2543f?avr?08/04 figure 96. idle supply current vs. v cc (internal rc osc illator, 128 khz) power-down supply current figure 97. power-down supply current vs. v cc (watchdog timer disabled) idle supply current vs. v cc internal rc oscillator, 128 khz 85 c 25 c -40 c 0 0.005 0.01 0.015 0.02 0.025 0.03 0.035 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (m a) power-down supply current vs. v cc watchdog timer disabled 85 c 25 c -40 c 0 0.25 0.5 0.75 1 1.25 1.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua)
187 attiny2313/v 2543f?avr?08/04 figure 98. power-down supply current vs. v cc (watchdog timer enabled) standby supply current figure 99. standby supply current vs. v cc power-down supply current vs. v cc watchdog timer enabled 85 c 25 c -40 c 0 2 4 6 8 10 12 14 16 18 20 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) standby supply current vs. v cc 455khz res 2mhz xtal 2mhz res 1mhz res 0 0.01 0.02 0.03 0.04 0.05 0.06 0.07 0.08 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (m a)
188 attiny2313/v 2543f?avr?08/04 pin pull-up figure 100. i/o pin pull-up resistor current vs. input voltage (v cc = 5v) figure 101. i/o pin pull-up resistor current vs. input voltage (v cc = 2.7v) i/o pin pull-up resistor current vs. input voltage vcc = 5v 85 c 25 c -40 c 0 20 40 60 80 100 120 140 160 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 v op (v) i op (ua ) i/o pin pull-up resistor current vs. input voltage vcc = 2.7v 85 c 25 c -40 c 0 10 20 30 40 50 60 70 80 0 0.5 1 1.5 2 2.5 3 v op (v) i op (ua)
189 attiny2313/v 2543f?avr?08/04 figure 102. reset pull-up resistor current vs. reset pin voltage (v cc = 5v) figure 103. reset pull-up resistor current vs. reset pin voltage (v cc = 2.7v) reset pull-up resistor current vs. reset pin voltage vcc = 5v 85 c 25 c -40 c 0 20 40 60 80 100 120 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 v reset (v) i reset (ua) reset pull-up resistor current vs. reset pin voltage v cc = 2.7v 85 c 25 c -40 c 0 10 20 30 40 50 60 0 0.5 1 1.5 2 2.5 3 v reset (v) i reset (ua)
190 attiny2313/v 2543f?avr?08/04 pin driver strength figure 104. i/o pin source current vs. output voltage (v cc = 5v) figure 105. i/o pin source current vs. output voltage (v cc = 2.7v) i/o pin source current vs. output voltage vcc = 5v 85 c 25 c -40 c 0 10 20 30 40 50 60 70 80 90 3 3.2 3.4 3.6 3.8 4 4.2 4.4 4.6 4.8 5 v oh (v) i oh (ma) i/o pin source current vs. output voltage vcc = 2.7v 85 c 25 c -40 c 0 5 10 15 20 25 30 35 0.5 1 1.5 2 2.5 3 v oh (v) i oh (ma)
191 attiny2313/v 2543f?avr?08/04 figure 106. i/o pin source current vs. output voltage (v cc = 1.8v) figure 107. i/o pin sink current vs. output voltage (v cc = 5v) i/o pin source current vs. output voltage v cc = 1.8v 85 c 25 c -40 c 0 1 2 3 4 5 6 7 8 9 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 v oh (v) i oh (ma) i/o pin sink current vs. output voltage v cc = 5v 85 c 25 c -40 c 0 10 20 30 40 50 60 70 80 90 100 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 v ol (v) i ol (ma)
192 attiny2313/v 2543f?avr?08/04 figure 108. i/o pin sink current vs. output voltage (v cc = 2.7v) figure 109. i/o pin sink current vs. output voltage (v cc = 1.8v) i/o pin sink current vs. output voltage v cc = 2.7v 85 c 25 c -40 c 0 5 10 15 20 25 30 35 40 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 v ol (v) i ol (ma) i/o pin sink current vs. output voltage v cc = 1.8v 85 c 25 c -40 c 0 2 4 6 8 10 12 14 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 v ol (v) i ol (ma)
193 attiny2313/v 2543f?avr?08/04 figure 110. reset i/o pin source current vs. output voltage (v cc = 5v) figure 111. reset i/o pin source current vs. output voltage (v cc = 2.7v) reset i/o pin source current vs. output voltage v cc = 5v 85 c 25 c -40 c 0 2 4 6 8 10 12 14 16 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 v oh (v) current (ma) reset i/o pin source current vs. output voltage v cc = 2.7v 85 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 0 0.5 1 1.5 2 2.5 3 v oh (v) current (m a)
194 attiny2313/v 2543f?avr?08/04 figure 112. reset i/o pin source current vs. output voltage (v cc = 1.8v) figure 113. reset i/o pin sink current vs. output voltage (v cc = 5v) reset i/o pin source current vs. output voltage v cc = 1.8v 85 c 25 c -40 c 0 0.2 0.4 0.6 0.8 1 1.2 1.4 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 2 v oh (v) current (ma) reset i/o pin sink current vs. output voltage v cc = 5v 85 c 25 c -40 c 0 2 4 6 8 10 12 14 16 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 v ol (v) current (ma)
195 attiny2313/v 2543f?avr?08/04 figure 114. reset i/o pin sink current vs. output voltage (v cc = 2.7v) figure 115. reset i/o pin sink current vs. output voltage (v cc = 1.8v) reset i/o pin sink current vs. output voltage v cc = 2.7v 85 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 5 v ol (v) current (ma) reset i/o pin sink current vs. output voltage v cc = 1.8v 85 c 25 c -40 c 0 0.2 0.4 0.6 0.8 1 1.2 1.4 0 0.2 0.4 0.6 0.8 1 1.2 1.4 1.6 1.8 v ol (v) current (ma)
196 attiny2313/v 2543f?avr?08/04 pin thresholds and hysteresis figure 116. i/o pin input threshold voltage vs. v cc (v ih , i/o pin read as ?1?) figure 117. i/o pin input threshold voltage vs. v cc (v il , i/o pin read as ?0?) i/o pin input threshold voltage vs . v cc vih, io pin read as '1' 85 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v) i/o pin input threshold voltage vs. v cc vil, io pin read as '0' 85 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v)
197 attiny2313/v 2543f?avr?08/04 figure 118. reset i/o input threshold voltage vs. v cc (v ih ,reset pin read as ?1?) figure 119. reset i/o input threshold voltage vs. v cc (v il ,reset pin read as ?0?) reset i/o pin input threshold voltage vs. v cc vih, io pin read as '1' 85 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v) reset i/o pin input threshold voltage vs. v cc vil, io pin read as '0' 85c 25c -40c 0 0.5 1 1.5 2 2.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v)
198 attiny2313/v 2543f?avr?08/04 figure 120. reset i/o input pin hysteresis vs. v cc figure 121. reset input thresh old voltage vs. v cc (v ih ,reset pin read as ?1?) reset i/o input pin hysteresis vs. v cc 85 c 25 c -40 c 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) input hysteresis (v) reset input threshold voltage vs. v cc vih, io pin read as '1' 85 c 25 c -40 c 0 0.5 1 1.5 2 2.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v)
199 attiny2313/v 2543f?avr?08/04 figure 122. reset input thresh old voltage vs. v cc (v il ,reset pin read as ?0?) figure 123. reset input pin hysteresis vs. v cc reset input threshold voltage vs. v cc vil, io pin read as '0' 85 c 25 c -40 c 0 0.5 1 1.5 2 2.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) threshold (v) reset input pin hysteresis vs. v cc 85 c 25 c -40 c 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) input hysteresis (v)
200 attiny2313/v 2543f?avr?08/04 bod thresholds and analog comparator offset figure 124. bod thresholds vs. temperature (bod level is 4.3v) figure 125. bod thresholds vs. temperature (bod level is 2.7v) bod thresholds vs. temperature bodlevel is 4.3v 4.25 4.3 4.35 4.4 4.45 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 temperature (c) thres hol d (v ) rising vcc falling vcc bod thresholds vs. temperature bodlevel is 2.7v 2.65 2.7 2.75 2.8 2.85 -40-30-20-100 102030405060708090 temperature (c) threshold (v) rising vcc falling vcc
201 attiny2313/v 2543f?avr?08/04 figure 126. bod thresholds vs. temperature (bod level is 1.8v) internal oscillator speed figure 127. watchdog oscillator frequency vs. v cc bod thresholds vs. temperature bodlevel is 1.8v rising vcc falling vcc 1.78 1.8 1.82 1.84 1.86 1.88 -40-30-20-100 102030405060708090 temperature (c) threshold (v) watchdog oscillator frequency vs. vcc 85 c 25 c -40 c 0.095 0.096 0.097 0.098 0.099 0.1 0.101 0.102 0.103 0.104 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (m hz )
202 attiny2313/v 2543f?avr?08/04 figure 128. watchdog oscillator freq uency vs. temperature figure 129. calibrated 8 mhz rc oscillator frequen cy vs. temperature watchdog oscillator frequency vs. temperature 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 1.8 v 0.096 0.097 0.098 0.099 0.1 0.101 0.102 0.103 0.104 0.105 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 temperature (c) f rc (mhz) calibrated 8mhz rc oscillator frequency vs. temperature 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 1.8 v 7.7 7.8 7.9 8 8.1 8.2 8.3 8.4 -40-30-20-100 102030405060708090 temperature (c) f rc (mhz )
203 attiny2313/v 2543f?avr?08/04 figure 130. calibrated 8 mhz rc osc illator frequency vs. v cc figure 131. calibrated 8 mhz rc oscillator frequen cy vs. osccal value calibrated 8mhz rc oscillator frequency vs. v cc 85 c 25 c -40 c 7.7 7.8 7.9 8 8.1 8.2 8.3 8.4 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (mhz) calibrated 8mhz rc oscillator frequency vs. osccal value 25 c 0 2 4 6 8 10 12 14 0 163248648096112128 osccal value f rc (mhz)
204 attiny2313/v 2543f?avr?08/04 figure 132. calibrated 4 mhz rc oscillator frequen cy vs. temperature figure 133. calibrated 4 mhz rc osc illator frequency vs. v cc calibrated 4mhz rc oscillator frequency vs. temperature 5.5 v 5.0 v 3.3 v 1.8 v 3.9 3.95 4 4.05 4.1 4.15 4.2 -40-30-20-10 0 102030405060708090 temperature (c) f rc (mhz) calibrated 4mhz rc oscillator frequency vs. v cc 85 c 25 c -40 c 3.9 3.95 4 4.05 4.1 4.15 4.2 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) f rc (mhz)
205 attiny2313/v 2543f?avr?08/04 figure 134. calibrated 4 mhz rc oscillator frequen cy vs. osccal value current consumption of peripheral units figure 135. brownout detector current vs. v cc calibrated 4mhz rc oscillator frequency vs. osccal value 25 c 0 1 2 3 4 5 6 7 0 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 128 osccal value f rc (mhz ) brownout detector current vs. v cc 85 c 25 c -40 c 0 5 10 15 20 25 30 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua)
206 attiny2313/v 2543f?avr?08/04 figure 136. analog comparator current vs. v cc figure 137. programming current vs. v cc analog comparator current vs. v cc 85 c 25 c -40 c 0 10 20 30 40 50 60 70 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ua) programming current vs. v cc 85 c 25 c -40 c 0 0.5 1 1.5 2 2.5 3 3.5 4 4.5 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) i cc (ma)
207 attiny2313/v 2543f?avr?08/04 current consumption in reset and reset pulsewidth figure 138. reset supply current vs. v cc (0.1 - 1.0 mhz, excluding current through the reset pull-up) figure 139. reset supply current vs. v cc (1 - 20 mhz, excluding current through the reset pull-up) reset supply current vs. v cc 0.1 - 1.0 mhz, excluding current through the reset pullup 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 1.8 v 0 0.02 0.04 0.06 0.08 0.1 0.12 0.14 0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 frequency (mhz) i cc (ma) reset supply current vs. v cc 1 - 20 mhz, excluding current through the reset pullup 5.5 v 5.0 v 4.5 v 4.0 v 3.3 v 2.7 v 0 0.5 1 1.5 2 2.5 0 2 4 6 8 101214161820 frequency (mhz) i cc (ma)
208 attiny2313/v 2543f?avr?08/04 figure 140. minimum reset pulse width vs. v cc minimum reset pulse width vs. v cc 85 c 25 c -40 c 0 500 1000 1500 2000 2500 1.5 2 2.5 3 3.5 4 4.5 5 5.5 v cc (v) pulsewidth (ns)
209 attiny2313/v 2543f?avr?08/04 register summary address name bit 7 bit 6 bit 5 bit 4 bit 3 bit 2 bit 1 bit 0 page 0x3f (0x5f) sreg i t h s v n z c 7 0x3e (0x5e) reserved ? ? ? ? ? ? ? ? 0x3d (0x5d) spl sp7 sp6 sp5 sp4 sp3 sp2 sp1 sp0 10 0x3c (0x5c) ocr0b timer/counter0 ? compare register b 76 0x3b (0x5b) gimsk int1 int0 pcie ? ? ? ? ?59 0x3a (0x5a) eifr intf1 intf0 pcif ? ? ? ? ?60 0x39 (0x59) timsk toie1 ocie1a ocie1b ? icie1 ocie0b toie0 ocie0a 77, 108 0x38 (0x58) tifr tov1 ocf1a ocf1b ? icf1 ocf0b tov0 ocf0a 77 0x37 (0x57) spmcsr ? ? ? ctpb rflb pgwrt pgers selfprgen 154 0x36 (0x56) ocr0a timer/counter0 ? compare register a 76 0x35 (0x55) mcucr pud sm1 se sm0 isc11 isc10 isc01 isc00 52 0x34 (0x54) mcusr ? ? ? ? wdrf borf extrf porf 36 0x33 (0x53) tccr0b foc0a foc0b ? ? wgm02 cs02 cs01 cs00 75 0x32 (0x52) tcnt0 timer/counter0 (8-bit) 76 0x31 (0x51) osccal ? cal6 cal5 cal4 cal3 cal2 cal1 cal0 25 0x30 (0x50) tccr0a com0a1 com0a0 com0b1 com0b0 ? ?wgm01wgm00 72 0x2f (0x4f) tccr1a com1a1 com1a0 com1b1 com1bo ? ? wgm11 wgm10 103 0x2e (0x4e) tccr1b icnc1 ices1 ? wgm13 wgm12 cs12 cs11 cs10 106 0x2d (0x4d) tcnt1h timer/counter1 ? counter register high byte 107 0x2c (0x4c) tcnt1l timer/counter1 ? counter register low byte 107 0x2b (0x4b) ocr1ah timer/counter1 ? compare register a high byte 107 0x2a (0x4a) ocr1al timer/counter1 ? compare register a low byte 107 0x29 (0x49) ocr1bh timer/counter1 ? compare register b high byte 108 0x28 (0x48) ocr1bl timer/counter1 ? compare register b low byte 108 0x27 (0x47) reserved ? ? ? ? ? ? ? ? 0x26 (0x46) clkpr clkpce ? ? ? clkps3 clkps2 clkps1 clkps0 27 0x25 (0x45) icr1h timer/counter1 - input capture register high byte 108 0x24 (0x44) icr1l timer/counter1 - input capture register low byte 108 0x23 (0x43) gtccr ? ? ? ? ? ? ? psr10 80 0x22 (ox42) tccr1c foc1a foc1b ? ? ? ? ? ? 107 0x21 (0x41) wdtcsr wdif wdie wdp3 wdce wde wdp2 wdp1 wdp0 41 0x20 (0x40) pcmsk pcint7 pcint6 pcint 5 pcint4 pcint3 pcint2 pcint1 pcint0 60 0x1f (0x3f) reserved ? ? ? ? ? ? ? ? 0x1e (0x3e) eear ? eeprom address register 15 0x1d (0x3d) eedr eeprom data register 16 0x1c (0x3c) eecr ? ? eepm1 eepm0 eerie eempe eepe eere 16 0x1b (0x3b) porta ? ? ? ? ? portr2 porta1 porta0 57 0x1a (0x3a) ddra ? ? ? ? ? dda2 dda1 dda0 57 0x19 (0x39) pina ? ? ? ? ? pina2 pina1 pina0 57 0x18 (0x38) portb portb7 portb6 portb 5 portb4 portb3 portb2 portb1 portb0 57 0x17 (0x37) ddrb ddb7 ddb6 ddb 5 ddb4 ddb3 ddb2 ddb1 ddb0 57 0x16 (0x36) pinb pinb7 pinb6 pinb5 pinb4 pinb3 pinb2 pinb1 pinb0 57 0x15 (0x35) gpior2 general purpose i/o register 2 20 0x14 (0x34) gpior1 general purpose i/o register 1 20 0x13 (0x33) gpior0 general purpose i/o register 0 20 0x12 (0x32) portd ? portd6 portd5 portd4 portd3 portd2 portd1 portd0 57 0x11 (0x31) ddrd ? ddd6 ddd5 ddd4 ddd3 ddd2 ddd1 ddd0 57 0x10 (0x30) pind ? pind6 pind5 pind4 pind3 pind2 pind1 pind0 57 0x0f (0x2f) usidr usi data register 143 0x0e (0x2e) usisr usisif usioif usipf usidc usicnt3 usicnt2 usicnt1 usicnt0 144 0x0d (0x2d) usicr usisie usioie usiwm1 usiwm0 usics1 usics0 usiclk usitc 145 0x0c (0x2c) udr uart data register (8-bit) 128 0x0b (0x2b) ucsra rxc txc udre fe dor upe u2x mpcm 128 0x0a (0x2a) ucsrb rxcie txcie udrie rxen txen ucsz2 rxb8 txb8 130 0x09 (0x29) ubrrl ubrrh[7:0] 132 0x08 (0x28) acsr acd acbg aco aci acie acic acis1 acis0 148 0x07 (0x27) reserved ? ? ? ? ? ? ? ? 0x06 (0x26) reserved ? ? ? ? ? ? ? ? 0x05 (0x25) reserved ? ? ? ? ? ? ? ? 0x04 (0x24) reserved ? ? ? ? ? ? ? ? 0x03 (0x23) ucsrc ? umsel upm1 upm0 usbs ucsz1 ucsz0 ucpol 131 0x02 (0x22) ubrrh ? ? ? ? ubrrh[11:8] 132 0x01 (0x21) didr ? ? ? ? ? ? ain1d ain0d 149 0x00 (0x20) reserved ? ? ? ? ? ? ? ?
210 attiny2313/v 2543f?avr?08/04 note: 1. for compatibility with future devices, reserved bits shoul d be written to zero if accessed. reserved i/o memory addresse s should never be written. 2. i/o registers within the address range 0x00 - 0x1f are direct ly bit-accessible using the sbi and cbi instructions. in these registers, the value of single bits can be ch ecked by using the sbis and sbic instructions. 3. some of the status flags are cleared by writing a logical one to them. note that, unlike most other avrs, the cbi and sbi instructions will only operate on the specified bit, and can ther efore be used on registers containi ng such status flags. the cbi and sbi instructions work wit h registers 0x00 to 0x1f only. 4. when using the i/o specific commands in and out, the i/o addresses 0x00 - 0x3f must be used. when addressing i/o registers as data space using ld and st instru ctions, 0x20 must be added to these addresses.
211 attiny2313/v 2543f?avr?08/04 instruction set summary mnemonics operands description operation flags #clocks arithmetic and logic instructions add rd, rr add two registers rd rd + rr z,c,n,v,h 1 adc rd, rr add with carry two registers rd rd + rr + c z,c,n,v,h 1 adiw rdl,k add immediate to word rdh:rdl rdh:rdl + k z,c,n,v,s 2 sub rd, rr subtract two registers rd rd - rr z,c,n,v,h 1 subi rd, k subtract constant from register rd rd - k z,c,n,v,h 1 sbc rd, rr subtract with carry two registers rd rd - rr - c z,c,n,v,h 1 sbci rd, k subtract with carry constant from reg. rd rd - k - c z,c,n,v,h 1 sbiw rdl,k subtract immediate from word rdh:rdl rdh:rdl - k z,c,n,v,s 2 and rd, rr logical and registers rd rd ? rr z,n,v 1 andi rd, k logical and register and constant rd rd ? k z,n,v 1 or rd, rr logical or registers rd rd v rr z,n,v 1 ori rd, k logical or register and constant rd rd v k z,n,v 1 eor rd, rr exclusive or registers rd rd rr z,n,v 1 com rd one?s complement rd 0xff ? rd z,c,n,v 1 neg rd two?s complement rd 0x00 ? rd z,c,n,v,h 1 sbr rd,k set bit(s) in register rd rd v k z,n,v 1 cbr rd,k clear bit(s) in register rd rd ? (0xff - k) z,n,v 1 inc rd increment rd rd + 1 z,n,v 1 dec rd decrement rd rd ? 1 z,n,v 1 tst rd test for zero or minus rd rd ? rd z,n,v 1 clr rd clear register rd rd rd z,n,v 1 ser rd set register rd 0xff none 1 branch instructions rjmp k relative jump pc pc + k + 1 none 2 ijmp indirect jump to (z) pc z none 2 rcall k relative subroutine call pc pc + k + 1 none 3 icall indirect call to (z) pc znone3 ret subroutine return pc stack none 4 reti interrupt return pc stack i 4 cpse rd,rr compare, skip if equal if (rd = rr) pc pc + 2 or 3 none 1/2/3 cp rd,rr compare rd ? rr z, n,v,c,h 1 cpc rd,rr compare with carry rd ? rr ? c z, n,v,c,h 1 cpi rd,k compare register with immediate rd ? k z, n,v,c,h 1 sbrc rr, b skip if bit in register cleared if (rr(b)=0) pc pc + 2 or 3 none 1/2/3 sbrs rr, b skip if bit in register is set if (rr(b)=1) pc pc + 2 or 3 none 1/2/3 sbic p, b skip if bit in i/o register cleared if (p(b)=0) pc pc + 2 or 3 none 1/2/3 sbis p, b skip if bit in i/o register is set if (p(b)=1) pc pc + 2 or 3 none 1/2/3 brbs s, k branch if status flag set if (sreg(s) = 1) then pc pc+k + 1 none 1/2 brbc s, k branch if status flag cleared if (sreg(s) = 0) then pc pc+k + 1 none 1/2 breq k branch if equal if (z = 1) then pc pc + k + 1 none 1/2 brne k branch if not equal if (z = 0) then pc pc + k + 1 none 1/2 brcs k branch if carry set if (c = 1) then pc pc + k + 1 none 1/2 brcc k branch if carry cleared if (c = 0) then pc pc + k + 1 none 1/2 brsh k branch if same or higher if (c = 0) then pc pc + k + 1 none 1/2 brlo k branch if lower if (c = 1) then pc pc + k + 1 none 1/2 brmi k branch if minus if (n = 1) then pc pc + k + 1 none 1/2 brpl k branch if plus if (n = 0) then pc pc + k + 1 none 1/2 brge k branch if greater or equal, signed if (n v= 0) then pc pc + k + 1 none 1/2 brlt k branch if less than zero, signed if (n v= 1) then pc pc + k + 1 none 1/2 brhs k branch if half carry flag set if (h = 1) then pc pc + k + 1 none 1/2 brhc k branch if half carry flag cleared if (h = 0) then pc pc + k + 1 none 1/2 brts k branch if t flag set if (t = 1) then pc pc + k + 1 none 1/2 brtc k branch if t flag cleared if (t = 0) then pc pc + k + 1 none 1/2 brvs k branch if overflow flag is set if (v = 1) then pc pc + k + 1 none 1/2 brvc k branch if overflow flag is cleared if (v = 0) then pc pc + k + 1 none 1/2 brie k branch if interrupt enabled if ( i = 1) then pc pc + k + 1 none 1/2 brid k branch if interrupt disabled if ( i = 0) then pc pc + k + 1 none 1/2 bit and bit-test instructions sbi p,b set bit in i/o register i/o(p,b) 1none2 cbi p,b clear bit in i/o register i/o(p,b) 0none2 lsl rd logical shift left rd(n+1) rd(n), rd(0) 0 z,c,n,v 1 lsr rd logical shift right rd(n) rd(n+1), rd(7) 0 z,c,n,v 1 rol rd rotate left through carry rd(0) c,rd(n+1) rd(n),c rd(7) z,c,n,v 1
212 attiny2313/v 2543f?avr?08/04 ror rd rotate right through carry rd(7) c,rd(n) rd(n+1),c rd(0) z,c,n,v 1 asr rd arithmetic shift right rd(n) rd(n+1), n=0..6 z,c,n,v 1 swap rd swap nibbles rd(3..0) rd(7..4),rd(7..4) rd(3..0) none 1 bset s flag set sreg(s) 1 sreg(s) 1 bclr s flag clear sreg(s) 0 sreg(s) 1 bst rr, b bit store from register to t t rr(b) t 1 bld rd, b bit load from t to register rd(b) tnone1 sec set carry c 1c1 clc clear carry c 0 c 1 sen set negative flag n 1n1 cln clear negative flag n 0 n 1 sez set zero flag z 1z1 clz clear ze ro flag z 0 z 1 sei global interrupt enable i 1i1 cli global interrupt disable i 0 i 1 ses set signed test flag s 1s1 cls clear signed test flag s 0 s 1 sev set twos complement overflow. v 1v1 clv clear twos complement overflow v 0 v 1 set set t in sreg t 1t1 clt clear t in sreg t 0 t 1 seh set half carry flag in sreg h 1h1 clh clear half carry flag in sreg h 0 h 1 data transfer instructions mov rd, rr move between registers rd rr none 1 movw rd, rr copy register word rd+1:rd rr+1:rr none 1 ldi rd, k load immediate rd knone1 ld rd, x load indirect rd (x) none 2 ld rd, x+ load indirect and post-inc. rd (x), x x + 1 none 2 ld rd, - x load indirect and pre-dec. x x - 1, rd (x) none 2 ld rd, y load indirect rd (y) none 2 ld rd, y+ load indirect and post-inc. rd (y), y y + 1 none 2 ld rd, - y load indirect and pre-dec. y y - 1, rd (y) none 2 ldd rd,y+q load indirect with displacement rd (y + q) none 2 ld rd, z load indirect rd (z) none 2 ld rd, z+ load indirect and post-inc. rd (z), z z+1 none 2 ld rd, -z load indirect and pre-dec. z z - 1, rd (z) none 2 ldd rd, z+q load indirect with displacement rd (z + q) none 2 lds rd, k load direct from sram rd (k) none 2 st x, rr store indirect (x) rr none 2 st x+, rr store indirect and post-inc. (x) rr, x x + 1 none 2 st - x, rr store indirect and pre-dec. x x - 1, (x) rr none 2 st y, rr store indirect (y) rr none 2 st y+, rr store indirect and post-inc. (y) rr, y y + 1 none 2 st - y, rr store indirect and pre-dec. y y - 1, (y) rr none 2 std y+q,rr store indirect with displacement (y + q) rr none 2 st z, rr store indirect (z) rr none 2 st z+, rr store indirect and post-inc. (z) rr, z z + 1 none 2 st -z, rr store indirect and pre-dec. z z - 1, (z) rr none 2 std z+q,rr store indirect with displacement (z + q) rr none 2 sts k, rr store direct to sram (k) rr none 2 lpm load program memory r0 (z) none 3 lpm rd, z load program memory rd (z) none 3 lpm rd, z+ load program memory and post-inc rd (z), z z+1 none 3 spm store program memory (z) r1:r0 none - in rd, p in port rd pnone1 out p, rr out port p rr none 1 push rr push register on stack stack rr none 2 pop rd pop register from stack rd stack none 2 mcu control instructions nop no operation none 1 sleep sleep (see specific descr. for sleep function) none 1 wdr watchdog reset (see specific descr. for wdr/timer) none 1 break break for on-chip debug only none n/a mnemonics operands description operation flags #clocks
213 attiny2313/v 2543f?avr?08/04 ordering information note: 1. this device can also be supplied in wafer form. please contact your local atmel sales office for detailed ordering infor mation and minimum quantities. 2. pb-free packaging alternative. 3. see figure 81 on page 178 and figure 82 on page 178. speed (mhz) power supply ordering code package (1) operation range 10 (3) 1.8 - 5.5v attiny2313v-10pi attiny2313v-10pj (2) ATTINY2313V-10SI attiny2313v-10sj (2) 20p3 20p3 20s 20s industrial (-4 0 c to 85 c) 20 (3) 2.7 - 5.5v attiny2313-20pi attiny2313-20pj (2) attiny2313-20si attiny2313-20sj (2) 20p3 20p3 20s 20s industrial (-4 0 c to 85 c) package type 20p3 20-lead, 0.300" wide, plastic dual inline package (pdip) 20s 20-lead, 0.300" wide, plastic gull wing small outline (soic)
214 attiny2313/v 2543f?avr?08/04 packaging information 20p3 2325 orchard parkway san jose, ca 95131 title drawing no. r rev. 20p3 , 20-lead (0.300"/7.62 mm wide) plastic dual inline package (pdip) c 20p3 1/12/04 pin 1 e1 a1 b e b1 c l seating plane a d e eb ec common dimensions (unit of measure = mm) symbol min nom max note a ? ? 5.334 a1 0.381 ? ? d 25.493 ? 25.984 note 2 e 7.620 ? 8.255 e1 6.096 ? 7.112 note 2 b 0.356 ? 0.559 b1 1.270 ? 1.551 l 2.921 ? 3.810 c 0.203 ? 0.356 eb ? ? 10.922 ec 0.000 ? 1.524 e 2.540 typ notes: 1. this package conforms to jedec reference ms-001, variation ad. 2. dimensions d and e1 do not include mold flash or protrusion. mold flash or protrusion shall not exceed 0.25 mm (0.010").
215 attiny2313/v 2543f?avr?08/04 20s 2325 orchard parkway san jose, ca 95131 title drawing no. r rev. 20s2 , 20-lead, 0.300" wide body, plastic gull wing small outline package (soic) 1/9/02 20s2 a l a1 end view side view top view h e b n 1 e a d c common dimensions (unit of measure = inches) symbol min nom max note notes: 1. this drawing is for general information only; refer to jedec drawing ms-013, variation ac for additional information. 2. dimension "d" does not include mold flash, protrusions or gate burrs. mold flash, protrusions and gate burrs shall not exc eed 0.15 mm (0.006") per side. 3. dimension "e" does not include inter-lead flash or protrusion. inter-lead flash and protrusions shall not exceed 0.25 mm (0.010") per side. 4. "l" is the length of the terminal for soldering to a substrate. 5. the lead width "b", as measured 0.36 mm (0.014") or greater above the seating plane, shall not exceed a maximum value of 0.61 mm (0.024") per side. a 0.0926 0.1043 a1 0.0040 0.0118 b 0.0130 0.0200 4 c 0.0091 0.0125 d 0.4961 0.5118 1 e 0.2914 0.2992 2 h 0.3940 0.4190 l 0.0160 0.050 3 e 0.050 bsc
216 attiny2313/v 2543f?avr?08/04 errata the revision in this section refers to the revision of the attiny2313 device. attiny2313 rev b  wrong values read after erase only operation  parallel programming does not work  watchdog timer interrupt disabled 1. wrong values read after erase only operation at supply voltages below 2.7 v, an eeprom location that is erased by the erase only operation may read as programmed (0x00). problem fix/workaround if it is necessary to read an eeprom location after eras e only, use an atomic write operation with 0xff as data in order to erase a location. in any case, the write only operation can be used as intended. thus no special considerations are needed as long as the erased location is not read before it is programmed. 2. parallel programming does not work parallel programming is not functioning correctly. because of this, reprogramming of the device is impossible if one of the following modes are selected: ? in-system programming disabled (spien unprogrammed) ? reset disabled (rstdisbl programmed) problem fix/workaround serial programming is still wo rking correctly. by avoiding the two modes above, the device can be reprogrammed serially. 3. watchdog timer interrupt disabled if the watchdog timer interrupt flag is not cleared before a new timeout occurs, the watchdog will be disabled, and the interrupt flag will automatically be cleared. this is only applicable in interrupt only mode. if the watchdog is configured to reset the device in the watchdog time-out following an interrupt, the device works correctly. problem fix / workaround make sure there is enough time to always service the first timeout event before a new watchdog timeout occurs. this is done by selecting a long enough time-out period. attiny2313 rev a revision a has not been sampled.
217 attiny2313/v 2543f?avr?08/04 datasheet change log for attiny2313 please note that the referring page numbers in this section are referred to this docu- ment. the referring revision in this section are referring to the document revision. changes from rev. 2514e-04/04 to rev. 2514f-08/04 changes from rev. 2514d-03/04 to rev. 2514e-04/04 changes from rev. 2514c-12/03 to rev. 2514d-03/04 changes from rev. 2514b-09/03 to rev. 2514c-12/03 1. updated ?features? on page 1. 2. updated ?alternate functions of port b? on page 52. 3. updated ?calibration byte? on page 159. 4. moved table 69 on page 159 and table 70 on page 160 to ?page size? on page 159. 5. updated ?enter programming mode? on page 162. 6. updated ?serial programming algorithm? on page 172. 7. updated table 78 on page 173. 8. updated ?dc characteristics? on page 176. 9. updated ?attiny2313 typical characteristics? on page 179. 10. changed occurences of pcint15 to pcint7, eemwe to eempe and eewe to eepe in the document. 1. speed grades changed - 12mhz to 10mhz - 24mhz to 20mhz 2. updated figure 1 on page 2. 3. updated ?ordering information? on page 213. 4. updated ?maximum speed vs. vcc? on page 178. 5. updated ?attiny2313 typical characteristics? on page 179. 1. updated table 2 on page 22. 2. replaced ?watchdog timer? on page 38. 3. added ?maximum speed vs. vcc? on page 178. 4. ?serial programming algorithm? on page 172 updated. 5. changed ma to a in preliminary figure 135 on page 205. 6. ?ordering information? on page 213 updated. mlf package option removed 7. package drawing ?20p3? on page 214 updated. 8. updated c-code examples. 9. renamed instances of spmen to selfprgen, self programming enable. 1. updated ?calibrated internal rc oscillator? on page 24.
218 attiny2313/v 2543f?avr?08/04 changes from rev. 2514a-09/03 to rev. 2514b-09/03 1. fixed typo from uart to usart and updated speed grades and power consumption estimates in ?features? on page 1. 2. updated ?pin configurations? on page 2. 3. updated table 15 on page 33 and table 80 on page 177. 4. updated item 5 in ?serial programming algorithm? on page 172. 5. updated ?electrical characteristics? on page 176. 6. updated figure 81 on page 178 and added figure 82 on page 178. 7. changed sfior to gtccr in ?r egister summary? on page 209. 8. updated ?ordering information? on page 213. 9. added new errata in ?errata? on page 216.
i attiny2313/v 2543f?avr?08/04 table of contents features............... .............. .............. ............... .............. .............. .......... 1 pin configurations............ .............. ............... .............. .............. .......... 2 overview.............. .............. .............. ............... .............. .............. .......... 2 block diagram ...................................................................................................... 3 pin descriptions.................................................................................................... 5 about code examples........... ................ ................. ................ ............. 5 disclaimer............ .............. .............. ............... .............. .............. .......... 5 avr cpu core ................ ................ ............... .............. .............. .......... 6 introduction ........................................................................................................... 6 architectural overview.......................................................................................... 6 alu ? arithmetic logic unit.................................................................................. 7 status register ..................................................................................................... 7 general purpose register file ............................................................................. 8 stack pointer ...................................................................................................... 10 instruction execution timing............................................................................... 10 reset and interrupt handling.............................................................................. 11 avr attiny2313 memories ..... ................. ................ .............. ........... 13 in-system reprogrammable flash program memory ........................................ 13 sram data memory........................................................................................... 14 eeprom data memory............ ................ ................ ................ ................ .......... 15 i/o memory ......................................................................................................... 20 system clock and clock options ............. .............. .............. ........... 21 clock systems and their distribution .................................................................. 21 clock sources..................................................................................................... 22 default clock source .......................................................................................... 22 crystal oscillator................................................................................................. 22 calibrated internal rc oscillator .............. .......................................................... 24 external clock..................................................................................................... 26 128 khz internal oscillator.................................................................................. 27 power management and sleep modes......... .............. .............. ........ 29 idle mode ............................................................................................................ 29 power-down mode.............................................................................................. 30 standby mode..................................................................................................... 30 minimizing power consumption ......................................................................... 30 system control and reset ..... ............... ................. ................ ........... 32 internal voltage reference ................................................................................. 37 watchdog timer ................................................................................................. 38
ii attiny2313/v 2543f?avr?08/04 interrupts ................ ................ ................ ................. ................ ........... 43 interrupt vectors in attiny2313 .......................................................................... 43 i/o-ports........ ................. ................ .............. .............. .............. ........... 45 introduction ......................................................................................................... 45 ports as general digital i/o ................................................................................ 46 alternate port functions ..................................................................................... 50 register description for i/o-ports....................................................................... 57 external interrupts.......... .............. .............. .............. .............. ........... 58 8-bit timer/counter0 with pw m............... ................ .............. ........... 61 overview............................................................................................................. 61 timer/counter clock sources............................................................................. 62 counter unit........................................................................................................ 62 output compare unit.......................................................................................... 63 compare match output unit ............................................................................... 64 modes of operation ............................................................................................ 65 timer/counter timing diagrams......................................................................... 70 8-bit timer/counter register description ........................................................... 72 timer/counter0 and timer/counter1 pr escalers ............. ............... 79 16-bit timer/counter1.......... ................ ................. ................ ............. 81 overview............................................................................................................. 81 accessing 16-bit registers ................................................................................. 83 timer/counter clock sources............................................................................. 87 counter unit........................................................................................................ 87 input capture unit............................................................................................... 88 output compare units ........................................................................................ 90 compare match output unit ............................................................................... 92 modes of operation ............................................................................................ 93 timer/counter timing diagrams....................................................................... 101 16-bit timer/counter register description ....................................................... 103 usart ............... .............. .............. .............. .............. .............. ......... 110 overview........................................................................................................... 110 clock generation .............................................................................................. 111 frame formats ................................................................................................. 114 usart initialization.......................................................................................... 115 data transmission ? the usart transmitter ................................................. 117 data reception ? the usart receiver .......................................................... 120 asynchronous data reception ......................................................................... 123 multi-processor communication mode ............................................................. 127 usart register description ............................................................................ 128 examples of baud rate setting........................................................................ 133
iii attiny2313/v 2543f?avr?08/04 universal serial interface ? usi.......... ................. ................ ........... 137 overview........................................................................................................... 137 functional descriptions .................................................................................... 138 alternative usi usage ...................................................................................... 143 usi register descriptions................................................................................. 143 analog comparator ............. ................ ................. ................ ........... 148 debugwire on-chip debug s ystem .............. .............. ............ ...... 150 features............................................................................................................ 150 overview........................................................................................................... 150 physical interface ............................................................................................. 150 software break points ...................................................................................... 151 limitations of debugwire ................................................................................ 151 debugwire related register in i/o memory ................................................... 151 self-programming the flash... ................. ................ .............. ......... 152 addressing the flash during self-programming .............................................. 153 memory programming........... ................ ................. ................ ......... 157 program and data memory lock bits .............................................................. 157 fuse bits........................................................................................................... 158 signature bytes ................................................................................................ 159 calibration byte ................................................................................................ 159 page size ......................................................................................................... 159 parallel programming parameters, pin mapping, and commands .................. 160 serial programming pin mapping ..................................................................... 162 parallel programming ....................................................................................... 162 serial downloading........................................................................................... 171 electrical characteristics...... ................ ................. ................ ......... 176 absolute maximum ratings*............................................................................. 176 dc characteristics............................................................................................ 176 external clock drive waveforms ...................................................................... 177 external clock drive ......................................................................................... 177 maximum speed vs. v cc ........................................................................................................................ 178 attiny2313 typical characteristi cs ............... .............. ............ ...... 179 register summary ..... ................. ................ .............. .............. ......... 209 instruction set summary ...... ................ ................. ................ ......... 211 ordering information........... ................ ................. ................ ........... 213 packaging information .......... ................ ................. ................ ......... 214
iv attiny2313/v 2543f?avr?08/04 20p3 ................................................................................................................. 214 20s ................................................................................................................... 215 errata ............... ................ .............. .............. .............. .............. ......... 216 attiny2313 rev b............................................................................................. 216 attiny2313 rev a............................................................................................. 216 datasheet change log for attiny2313.......... .............. ............ ...... 217 changes from rev. 2514e-04/04 to rev. 2514f-08/04 ................................... 217 changes from rev. 2514d-03/04 to rev. 2514e-04/04 ................................... 217 changes from rev. 2514c-12/03 to rev. 2514d-03/04................................... 217 changes from rev. 2514b-09/03 to rev. 2514c-12/03 ................................... 217 changes from rev. 2514a-09/03 to rev. 2514b-09/03 ................................... 218 table of contents ................ .............. .............. .............. .............. ......... i
printed on recycled paper. disclaimer: atmel corporation makes no warranty for the use of its products , other than those expressly contained in the company?s standar d warranty which is detailed in atmel?s terms and conditions locat ed on the company?s web site. the company assumes no responsibi lity for any errors which may appear in this document, reserves the right to change devices or specifications detailed herein at any time wi thout notice, and does not make any commitment to update the information contained her ein. no licenses to patents or other intellectual property of atmel are granted by the company in connection with the sale of atmel produc ts, expressly or by implication. atmel?s products are not aut horized for use as critical components in life support devices or systems. atmel corporation atmel operations 2325 orchard parkway san jose, ca 95131, usa tel: 1(408) 441-0311 fax: 1(408) 487-2600 regional headquarters europe atmel sarl route des arsenaux 41 case postale 80 ch-1705 fribourg switzerland tel: (41) 26-426-5555 fax: (41) 26-426-5500 asia room 1219 chinachem golden plaza 77 mody road tsimshatsui east kowloon hong kong tel: (852) 2721-9778 fax: (852) 2722-1369 japan 9f, tonetsu shinkawa bldg. 1-24-8 shinkawa chuo-ku, tokyo 104-0033 japan tel: (81) 3-3523-3551 fax: (81) 3-3523-7581 memory 2325 orchard parkway san jose, ca 95131, usa tel: 1(408) 441-0311 fax: 1(408) 436-4314 microcontrollers 2325 orchard parkway san jose, ca 95131, usa tel: 1(408) 441-0311 fax: 1(408) 436-4314 la chantrerie bp 70602 44306 nantes cedex 3, france tel: (33) 2-40-18-18-18 fax: (33) 2-40-18-19-60 asic/assp/smart cards zone industrielle 13106 rousset cedex, france tel: (33) 4-42-53-60-00 fax: (33) 4-42-53-60-01 1150 east cheyenne mtn. blvd. colorado springs, co 80906, usa tel: 1(719) 576-3300 fax: 1(719) 540-1759 scottish enterprise technology park maxwell building east kilbride g75 0qr, scotland tel: (44) 1355-803-000 fax: (44) 1355-242-743 rf/automotive theresienstrasse 2 postfach 3535 74025 heilbronn, germany tel: (49) 71-31-67-0 fax: (49) 71-31-67-2340 1150 east cheyenne mtn. blvd. colorado springs, co 80906, usa tel: 1(719) 576-3300 fax: 1(719) 540-1759 biometrics/imagin g/hi-rel mpu/ high speed converters/rf datacom avenue de rochepleine bp 123 38521 saint-egreve cedex, france tel: (33) 4-76-58-30-00 fax: (33) 4-76-58-34-80 literature requests www.atmel.com/literature 2543f?avr?08/04 ? atmel corporation 2004 . all rights reserved. atmel ? and combinations thereof, avr ? , and avr studio ? are the registered trademarks of atmel corporation or its subsidiaries. microsoft ? , windows ? , windows nt ? , and windows xp ? are the registered trademar ks of microsoft corpo- ration. other terms and product names may be the trademarks of others


▲Up To Search▲   

 
Price & Availability of ATTINY2313V-10SI

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X